Object Declarations
In this page:
object ObjectName {
val property: Type = value
fun method() { }
}
ObjectName.property
ObjectName.method()
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
// Define the singleton object `AppConfig`
object AppConfig {
// Declare a read-only variable `appName`, set to `"MyApp"`
val appName = "MyApp"
// Declare a mutable variable `debugMode`, initialized to `false`
var debugMode = false
}
// Entry point: execution of the program starts here
fun main() {
// Print `AppConfig.appName` to the console, with a trailing newline
println(AppConfig.appName)
AppConfig.debugMode = true
// Print "Debug: ${AppConfig.debugMode}" to the console, with a trailing newline
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
// Define the singleton object `MathUtils`
object MathUtils {
fun square(x: Int) = x * x
fun cube(x: Int) = x * x * x
}
// Entry point: execution of the program starts here
fun main() {
// Print "Square of 5: ${MathUtils.square(5)}" to the console, with a trailing newline
println("Square of 5: ${MathUtils.square(5)}")
// Print "Cube of 3: ${MathUtils.cube(3)}" to the console, with a trailing newline
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
// Define the singleton object `Session`
object Session {
init {
// Print "Session object created" to the console, with a trailing newline
println("Session object created")
}
// Declare a read-only variable `id`, set to `"abc123"`
val id = "abc123"
}
// Entry point: execution of the program starts here
fun main() {
// Print "Before accessing Session" to the console, with a trailing newline
println("Before accessing Session")
// Print "Session id: ${Session.id}" to the console, with a trailing newline
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
// Define an interface `ClickListener` describing required behavior
interface ClickListener {
// Define the function `onClick` with no parameters
fun onClick()
}
// Entry point: execution of the program starts here
fun main() {
// Call `object : ClickListener` with a trailing lambda, storing the result in `listener`
val listener = object : ClickListener {
override fun onClick() {
// Print "Clicked!" to the console, with a trailing newline
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: