如何在伴随对象Kotlin中保留单例类对象的引用(How to keep the reference of the singleton class object in the companion object, Kotlin)

我要转换的代码如下:

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

android studio生成的代码是什么;

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

这段代码给了我错误,这是;

属性必须被初始化或是抽象的

我正在开发一个libgdx游戏,所以我会使用这种方法从我想要的任何地方使用Game对象。 它是一个单例类,所以它不会泄漏任何内存。

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;

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. It's a singleton class so it won't leak any memory.

最满意答案

使用lateinit来指示该字段稍后将被初始化。

companion object { lateinit var androidLauncher: AndroidLauncher }

Use lateinit to indicate that the field will be initialized later.

companion object { lateinit var androidLauncher: AndroidLauncher }

更多推荐