Singleton pattern is a common software design pattern. For example, beans in Spring are singletons by default. The singleton ensures that there is only one instance of a class in the system. That is, a class has only one object instance.

There are no static properties or methods in Kotlin, but you can declare an object instance object using the keyword object:

object User {
    val username: String = "admin"
    val password: String = "admin"

    fun hello(a) {
        println("Hello, object !")}}fun main(a){
    println(User.username) // Same as Java static class calls
    User.hello()
}
Copy the code

Companion objects are also provided in Kotlin, declared with the Companion object keyword:

class DataProcessor{
    companion object DataProcessor{

        fun process(a){
            println("I am processing data ...")}}}fun main(a){
    DataProcessor.process()
}
Copy the code

A class can have only one associated object.