Object Declarations
In this page:
Declaring a Singleton
object Name { ... } defines both the class and its single instance at once; there is no separate constructor call -- you simply refer to Name directly to use it.
Example: Declaring a Singleton
object AppConfig {
val appName = "MyApp"
var debugMode = false
}
fun main() {
println(AppConfig.appName)
AppConfig.debugMode = true
println("Debug: ${AppConfig.debugMode}")
}
Login to try C/C++/Java/PHP code in the editor
Object Declarations for Utility Functions
Objects are a natural place for stateless utility functions that logically belong together but don't need an instance per call.
Example: Object Declarations for Utility Functions
object MathUtils {
fun square(x: Int) = x * x
fun cube(x: Int) = x * x * x
}
fun main() {
println("Square of 5: ${MathUtils.square(5)}")
println("Cube of 3: ${MathUtils.cube(3)}")
}
Login to try C/C++/Java/PHP code in the editor
Lazy Initialization
An object's instance is created the first time it is accessed, not necessarily when the program starts, which can be observed by printing from its own init block.
Example: Lazy Initialization
object Session {
init {
println("Session object created")
}
val id = "abc123"
}
fun main() {
println("Before accessing Session")
println("Session id: ${Session.id}")
}
Login to try C/C++/Java/PHP code in the editor
Object Expressions for One-Off Instances
An anonymous object : Type { ... } creates a single-use instance implementing an interface or extending a class, useful for a quick, throwaway implementation without declaring a full named class.
Example: Object Expressions for One-Off Instances
interface ClickListener {
fun onClick()
}
fun main() {
val listener = object : ClickListener {
override fun onClick() {
println("Clicked!")
}
}
listener.onClick()
}
Login to try C/C++/Java/PHP code in the editor
- Trying to pass constructor arguments to an
objectdeclaration; singletons declared withobjectcannot take constructor parameters. - Forgetting an
objectis lazily initialized on first access, not at program startup, which can matter for side effects in itsinitblock. - Confusing
objectdeclarations (named singletons) with anonymousobjectexpressions used for one-off implementations.
object Name { ... }declares a singleton -- exactly one instance that is created lazily on first access.- Singletons cannot have constructor parameters since there is no explicit call to create them.
- An anonymous
object : SomeType { ... }(an object expression) creates a one-off instance implementing an interface or extending a class, often used where a Java anonymous class would be used. - Object declarations are commonly used for utility functions, constants, and shared state that should exist exactly once.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: