[英]Why can't object of nested class be used as a parameter of supertype constructor?
[英]Kotlin Object Supertype Constructor
我需要在Kotlin中實現單例MyClass
。
要求:
SuperClass
,我需要調用Superclass
的構造函數 MyClass
並且需要該上下文來調用Superclass
的構造函數。 MyClass
是一個單例。 相當於Java:
class MyClass extends SuperClass
{
// instance variable
// getInstance() method
MyClass(Context context)
{
super(context);
}
}
我試圖用一個object
解決這個問題,但沒有使它起作用。
有沒有一種方法可以使它與某個對象一起使用,還是必須使用一個companion object
?
考慮以下超類:
open class MySuperClass(val context: Context) {...}
由於Kotlin對象只有一個空的構造函數,因此您需要一個類似於以下內容的結構:
// Private constructor is only accessible within the class.
class MySingleton private constructor(context: Context) : MySuperClass(context) {
companion object {
lateinit var INSTANCE: MySingleton
// Instance setter is only accessible from within the class.
private set
// Custom init function is called from outside and replaces
// THE WHOLE SINGLETON with a new instance
// to avoid internal dependencies on the old context.
fun init(context: Context) {
INSTANCE = MySingleton(context.applicationContext)
}
}
// Lazily initialized field dependent on a Context instance.
val prefs by lazy { PreferenceManager.getDefaultSharedPreferences(context) }
}
在使用單例類之前,您需要調用一次init(context)
,而Application
是執行此操作的好地方。 每次Instant Run加載新的Application
對象時,這還將創建您的單例的新實例,因此您始終會獲得最新的應用程序上下文。
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// Eagerly initialized singleton.
MySingleton.init(this)
}
}
筆記:
class
而不是object
並自己管理當前實例。 如果需要將參數傳遞給單例的超類,則也必須這樣做。 getInstance(context)
的第一次調用時getInstance(context)
所以最好將單例對象中的重對象懶惰 。 您不需要任何對象或伴隨對象即可實現此目的。 這是在Kotlin中調用超類的構造函數的語法:
class MyClass(context: Context) : SuperClass(context)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.