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