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
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
}
}
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