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

421 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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

   companion object {
       lateinit var androidLauncher: AndroidLauncher
   }