![](/img/trans.png)
[英]Smart cast to ‘CLASS!’ is impossible, because ‘VARIABLE’ is a mutable property that could have been changed by this time
[英]smart cast impossible because instance is mutable property
我試圖在Kotlin中創建一個單例,並且遇到了問題,因為無法smart cast to PresenterManager is impossible because instance is mutable property that could have been changed at this time
。
這似乎是制作單例的一種非常標准的方法。 為什么它不讓我使用,我該如何解決?
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
}
}
}
這似乎是制作單例的一種非常標准的方法。
我建議您多讀一些有關Kotlin的文章。
object PresenterManager {
init {
// init code
}
fun whatever() {}
}
我上面寫的是科特林的一個單例。 現在,解釋一下您得到的消息:
無法將智能類型轉換為PresenterManager,因為實例是可變屬性,該屬性可能在此時已被更改
instance
是可為null的( private var instance: PresenterManager? = null
),並且getManager
函數期望返回非null的返回類型,因此解決此問題的多種方法之一是使getManager
返回可為null的類型( fun getManager(): PresenterManager?
)或使用!!
返回類型上的運算符。
要點是,如果您使用object
而不是class
來聲明您的單例,那么您實際上根本不需要該instance
變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.