Sobes.tech
Junior — Middle

Can you explain what is meant by 'object' in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the keyword object is used to declare a singleton — an object that is created once and accessible globally. This is a convenient way to create a single instance of a class without manually writing a singleton template.

Example:

object DatabaseConfig {
    val host = "localhost"
    val port = 5432

    fun connect() {
        println("Connecting to database at $host:$port")
    }
}

// Usage
DatabaseConfig.connect()

Additionally, object is used to create anonymous objects and companion objects, which allow creating static members within classes.