lateinit modifier is not allowed on primitive type properties in Kotlin

AndroidKotlin

Android Problem Overview


I am defining like a instance variable in kotlin and want to initialize it onCreate method of an activity.

var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Here I am getting a below error on count variable.

> Property must be initialized or be abstract in Kotlin

Well, I read this thread https://stackoverflow.com/questions/33849811/property-must-be-initialized-or-be-abstract and tried same but again I am getting a below error.

> lateinit modifier is not allowed on primitive type properties

lateinit var count: Int
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    count.inc()
}

Is there any way to do this in Kotlin ?

Android Solutions


Solution 1 - Android

There are several ways to resolve this issue.

You can Initialise it with default value (e.i 0 or -1 or whatever) and then initialise it whenever your logic says.

Or tell compiler that count will be initialised later in this code by using Delegates.notNull check notNull.

var count: Int by Delegates.notNull<Int>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // You can not call `Int.inc()` in onCreate()` function until `count` is initialised.
    // count.inc()
    // **initialise count** 
}

And if you need count value on demand (if not necessary to initialise in onCreate), you can use lazy function. Use this only if you have an intensive (Some calculation/Inflating a layout etc) task that you want to do on demand, Not to just assign a value.

var count:Int by lazy {
    // initialise
}

Now you can decide what to use.

I hope it helps.

Solution 2 - Android

There's no reason to leave it uninitialized. Just initialize it to 0 or -1.

lateinit is for non-null object references that can't easily be initialized in the class body definition.

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
QuestionN SharmaView Question on Stackoverflow
Solution 1 - Androidchandil03View Answer on Stackoverflow
Solution 2 - AndroidhasenView Answer on Stackoverflow