I'm trying to make a singleton in Kotlin and am running into problems because I get a smart cast to PresenterManager is impossible because instance is mutable property that could have been changed at this time
.
This seems like a pretty standard way to make a singleton. Why won't it let me and how can I fix it?
PresenterManager {
//some code
....
companion object {
private val PRESENTER_ID = "presenter_id"
private var instance: PresenterManager? = null
fun getManager(): PresenterManager {
if (instance == null) {
instance = PresenterManager(10, 30, TimeUnit.SECONDS)
}
return instance
}
}
}
This seems like a pretty standard way to make a singleton.
I do recommend you to read a bit more about Kotlin.
object PresenterManager {
init {
// init code
}
fun whatever() {}
}
What I wrote above is a Singleton in Kotlin. Now, to explain the message you are getting:
smart cast to PresenterManager is impossible because instance is mutable property that could have been changed at this time
instance
is nullable ( private var instance: PresenterManager? = null
), and the getManager
function expects a non-null return type, so one of the many ways of solving this is by either make getManager
return a nullable type ( fun getManager(): PresenterManager?
) or make use of the !!
operator on your return type.
The main point is that you really don't need of that instance
variable at all if you use an object
instead of a class
to declare your singleton.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.