Junior — Middle
How can the Singleton pattern be implemented in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the Singleton pattern is implemented very simply using the object keyword. This declaration creates a class with a single instance, which is initialized lazily and thread-safely.
Example:
object DatabaseConnection {
fun connect() {
println("Connecting to the database")
}
}
fun main() {
DatabaseConnection.connect() // calling the singleton method
}
Thus, object guarantees that the instance will be the only one in the application, and there is no need to write additional code to implement the Singleton pattern.