Singleton class in Kotlin

后端 未结 8 1860
梦如初夏
梦如初夏 2020-12-14 13:47

I want to know way to create singleton class, so that my Util class instantiate only once per app. However when I converted my Java class to kotlin, below code was generated

8条回答
  •  隐瞒了意图╮
    2020-12-14 14:42

    Only the word object is needed.

    object UtilProject {
        var bar: Int = 0
        fun foo() {        
        }
    }
    

    And you directly access the object that has only one instance

    fun main(args: Array) {
        UtilProject.bar = 1
        println(UtilProject.bar)    
    }
    

提交回复
热议问题