Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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.

Solution 2:

Use lateinit property

publicclassMyTest{
        lateinitvar subject: TestSubject

        funsetup() {
            subject = TestSubject()
        }

        funtest() {
            subject.method()
        } 
}

Post a Comment for "Kotlin Property With Getter. Can I Not Specify An Initial Value?"