Sobes.tech
Junior — Middle

Kas saaksite selgitada võtmesõna 'object' eesmärki ja kasutust Kotlin keeles?

sobes.tech AI

Vastus AI-lt

In Kotlin, the keyword object is used to declare a singleton — an object that is created once and is globally accessible. It is a convenient way to define a class and immediately create its single instance.

Additionally, 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 accessible throughout the application.