Junior — Middle
Can you explain the purpose and use of the 'object' keyword in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the keyword object is used to declare a singleton — an object that is created only once and is globally accessible. This is a convenient way to define a class and immediately create its single instance.
Also, object is used to create anonymous objects and companion objects, which allow defining static members inside a class.
Example with a singleton:
object DatabaseConnection {
fun connect() {
println("Connecting to the database")
}
}
fun main() {
DatabaseConnection.connect() // calling the singleton method
}
Here, DatabaseConnection is the only object available throughout the application.