问题描述
这肯定是个愚蠢的问题,但是我真的是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
这篇关于属性必须初始化或抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!