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

自作多情 提交于 2019-12-13 14:11:29

问题


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

回答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.




回答2:


Use lateinit property

public class MyTest {
        lateinit var subject: TestSubject

        fun setup() {
            subject = TestSubject()
        }

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


来源:https://stackoverflow.com/questions/48163095/kotlin-property-with-getter-can-i-not-specify-an-initial-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!