Kotlin属性与吸气剂.我可以不指定初始值吗? [英] Kotlin property with getter. Can I not specify an initial value?

查看:72
本文介绍了Kotlin属性与吸气剂.我可以不指定初始值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个单例类,但是不幸的是,Android几乎所有内容都需要Context,因此我需要它来创建实例.所以我只是假设用户名为init(),然后返回该实例.如下所示,如果_instance为null,则将引发异常,因此get方法不能返回null.

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.

但是Kotlin说我必须初始化instance.事实是,没有上下文就无法创建MyClass.因此,我不想指定初始值.我该怎么办?

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

推荐答案

var更改为val,它应该可以工作:

Change the var to val and it should work:

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

可变属性(var)不仅假定使用getter,而且假定使用setter.由于您未提供设置器,因此将生成默认设置器set(value) { field = value }.尽管在这种情况下毫无用处,但默认的setter使用field,因此需要对其进行初始化.

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.

这篇关于Kotlin属性与吸气剂.我可以不指定初始值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆