Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

android - Property must be initialized or be abstract

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

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

protected SharedPreferences mSharedPreferences;

And later in onCreate():

mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

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

I try to do same in Kotlin:

protected var sharedPreferences : SharedPreferences

And in onCreate():

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...