3

I want to create a singleton class, but unfortunately, Android needs Context for almost anything so I need it to create an instance. So I just assumed the user called init(), and then return the instance. As you see below, if the _instance is null, an exception will be thrown, so the get method cannot return null.

But Kotlin says I must initialise instance. The things is, that MyClass cannot be created without a context. So I would like not to specify an initial value. How can I do that?

companion object
{
    protected var _instance:MyClass? = null;
    fun init(context:Context)
    {
        _instance = MyClass(context)
    }
    var instance:MyClass //<---This causes a compile error.
        get()
        {
            if(_instance==null) throw RuntimeException("Call init() first.");
            return _instance!!;
        }
}
Damn Vegetables
  • 11,484
  • 13
  • 80
  • 135

2 Answers2

4

Change the var to val and it should work:

....
val instance: MyClass
....

A variable property (var) not only assumes a getter, but also a setter. Since you provided no setter, a default one was generated set(value) { field = value }. Despite is uselessness in this situation, the default setter uses field, thus requires its initialization.

voddan
  • 31,956
  • 8
  • 77
  • 87
1

Use lateinit property

public class MyTest {
        lateinit var subject: TestSubject

        fun setup() {
            subject = TestSubject()
        }

        fun test() {
            subject.method()
        } 
}
JEGADEESAN S
  • 566
  • 1
  • 6
  • 19
  • 2
    I think `lazy` is a lot more appropriate than `lateinit` in this case as it will kind of automatically call the setup() method – msrd0 Jan 09 '18 at 09:29