[英]smart cast impossible because instance is mutable property
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
. 我试图在Kotlin中创建一个单例,并且遇到了问题,因为无法
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. 我建议您多读一些有关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
无法将智能类型转换为PresenterManager,因为实例是可变属性,该属性可能在此时已被更改
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 !!
instance
是可为null的( private var instance: PresenterManager? = null
),并且getManager
函数期望返回非null的返回类型,因此解决此问题的多种方法之一是使getManager
返回可为null的类型( fun getManager(): PresenterManager?
)或使用!!
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. 要点是,如果您使用
object
而不是class
来声明您的单例,那么您实际上根本不需要该instance
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.