问题
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