Damn Vegetables
Damn Vegetables

Reputation: 12464

Kotlin property with getter. Can I not specify an initial value?

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!!;
        }
}

Upvotes: 3

Views: 1343

Answers (2)

voddan
voddan

Reputation: 33769

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.

Upvotes: 4

JEGADEESAN S
JEGADEESAN S

Reputation: 618

Use lateinit property

public class MyTest {
        lateinit var subject: TestSubject

        fun setup() {
            subject = TestSubject()
        }

        fun test() {
            subject.method()
        } 
}

Upvotes: 1

Related Questions