Junior
Can you explain the concept of an object in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, an object is a way to create a singleton, that is, a class with a single instance. Objects are declared using the object keyword and are initialized immediately. They can contain properties, methods, and implement interfaces.
Example:
object Database {
val name = "MyDB"
fun connect() {
println("Connecting to database $name")
}
}
fun main() {
Database.connect() // calling the object's method
}
Objects are useful when you need a single shared instance, for example, for storing settings or utilities.