Singleton class in Kotlin

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

    A Singleton example over retrofit to support the api call.

    object RetrofitClient {
    
        private var instance: Api? = null
        private val BASE_URL = "https://jsonplaceholder.typicode.com/"
    
        fun getInstance(): Api? {
            if (instance == null) {
                val retrofit = Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                instance = retrofit.create(Api::class.java)
            }
            return instance
        }
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题