Property must be initialized or be abstract

AndroidKotlin

Android Problem Overview


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"

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

Pulling this out of the comments from Alexander Udalov's answer for visibility. For nullable properties:

protected var sharedPreferences : SharedPreferences? = null

...and assign it a value later.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnton ShkurenkoView Question on Stackoverflow
Solution 1 - AndroidAlexander UdalovView Answer on Stackoverflow
Solution 2 - AndroidTom HowardView Answer on Stackoverflow