Kotlin对象超类型构造器

我需要在kotlin中实现一个单例MyClass

要求:

  1. MyClass有超类SuperClass ,我需要调用Superclass的构造函数
  2. 我需要将一个上下文传递给MyClass并需要上下文来调用Superclass的构造函数。
  3. 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会在每次Instant Run加载一个新的Application对象时创建一个新的单例实例,以便最终获得最新的应用程序上下文。

 class MyApplication : Application() { override fun onCreate() { super.onCreate() // Eagerly initialized singleton. MySingleton.init(this) } } 

笔记:

  • Kotlin对象只有一个空构造函数。 如果您需要初始化对象,请使用自定义的初始化函数。
  • 如果你的领域依赖于一个可能发生变化的上下文,那么最好使用class而不是object管理当前的实例。 如果你需要传递参数给你的单身人士的超类,你也必须这样做。
  • 因为你在应用程序开始的时候急切地初始化这个类(而不是第一次调用getInstance(context)所以懒惰地处理你的单例对象中的重对象是个好主意。
  • 如果您的应用程序是多进程的,只有在实际使用它的过程中才能找到初始化您的单例的方法。 (提示:ContentProvider默认只在主进程中创建。)

您不需要任何对象或伴侣对象来实现这一点。 这是在Kotlin中调用超类的构造函数的语法:

 class MyClass(context: Context) : SuperClass(context)