属性必须初始化或抽象 [英] Property must be initialized or be abstract

查看:101
本文介绍了属性必须初始化或抽象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这肯定是个愚蠢的问题,但是我真的是Kotlin的新手,我没有找到任何解决方案.

It must be stupid question, but I'm really new to Kotlin and I didn't find any solution.

如何声明类字段?就像我们可以在Java中使用它一样:

How to declare class field? Like we can have it in java:

protected SharedPreferences mSharedPreferences;

以及随后的onCreate()中:

mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

现在,我可以在任何地方使用它(在此基本活动的子类中).

Now I can use it anywhere I want (in subclasses of this base activity).

我尝试在Kotlin中做同样的事情:

I try to do same in Kotlin:

protected var sharedPreferences : SharedPreferences

onCreate()中:

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

但是我收到警告:属性必须初始化或抽象"

But I get a warning: "Property must be initialized or be abstract"

推荐答案

如果要在构造函数之外初始化属性,请

If you'd like to initialize a property outside the constructor, then late-initialized properties is what you may be looking for. Declare the property with the lateinit modifier, which will allow to skip the otherwise required initializer and will make the property access fail with exception until some meaningful value is assigned to it:

protected lateinit var sharedPreferences: SharedPreferences

这篇关于属性必须初始化或抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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