Singleton class in Kotlin

后端 未结 8 1887
梦如初夏
梦如初夏 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:50

    There is a special keyword object for singletons in Kotlin. You can just type something as simple as this to get working singleton class:

    object MySingleton
    

    or when you want some member functions:

    object MySingleton {
        fun someFunction(...) {...}
    }
    

    And then use it:

    MySingleton.someFunction(...)
    

    there is a reference: https://kotlinlang.org/docs/reference/object-declarations.html#object-declarations

    EDIT:

    In your case, you just need to replace in your definition of class UtilProject to this:

    object UtilProject {
    
        // here you put all member functions, values and variables
        // that you need in your singleton Util class, for example:
    
        val maxValue: Int = 100
    
        fun compareInts(a: Int, b: Int): Int {...}
    }
    

    And then you can simply use your singleton in other places:

    UtilProject.compareInts(1, 2)
    //or
    var value = UtilProject.maxValue
    

提交回复
热议问题