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

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

问题描述

这一定是个愚蠢的问题,但我对 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"

推荐答案

如果你想在构造函数之外初始化一个属性,那么 后期初始化的属性 是您可能正在寻找的.使用 lateinit 修饰符声明属性,这将允许跳过原本需要的初始化程序,并使属性访问失败并出现异常,直到为其分配了一些有意义的值:

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天全站免登陆