简体   繁体   English

如何在伴侣对象Kotlin中保留单例类对象的引用

[英]How to keep the reference of the singleton class object in the companion object, Kotlin

The code that I want to convert is the following; 我要转换的代码如下:

public class AndroidLauncher extends AndroidApplication {

   public static AndroidLauncher androidLauncher;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       androidLauncher = this;
   }
}

What android studio generated code is this; 这是什么android studio生成的代码;

class AndroidLauncher : AndroidApplication() {
   protected override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       androidLauncher = this
   }

   companion object {

       var androidLauncher: AndroidLauncher
   }
}

This code gives me error, which is; 这段代码给了我错误,那就是;

Property must be initialized or be abstract 属性必须初始化或抽象

I'm developing a game with libgdx, so I'll use this approach to use the Game object from anywhere I want. 我正在使用libgdx开发游戏,因此我将使用这种方法从所需的任何地方使用Game对象。 It's a singleton class so it won't leak any memory. 这是一个单例类,因此不会泄漏任何内存。

Use lateinit to indicate that the field will be initialized later. 使用lateinit表示该字段将在以后初始化。

   companion object {
       lateinit var androidLauncher: AndroidLauncher
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM