Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Property must be initialized or be abstract even if there is an init() function

I have converted this code from Java to Kotlin using Android Studio 3.0

internal var background: Drawable
internal var xMark: Drawable

private fun init() {
    background = ColorDrawable(Color.RED)
    xMark = ContextCompat.getDrawable(this@Subscriptions_main, R.drawable.delete)
}

On line 1 and 2 I'm getting the error:

Property must be initialized or be abstract

even though it is going to be initialized in the init function.

Is writing:

internal var background: Drawable? = null
internal var xMark: Drawable? = null

a viable and efficient solution? Is there any other better way?

like image 598
Daniele Avatar asked Nov 06 '17 14:11

Daniele


2 Answers

Before using lateinit, you must understand what that means.

Your variables are not initialized properly. Various ways to solve that problem:

  • Initialize the variables inside the constructor or a proper init block (not a private function as you declared it)
  • Initialize the variables at the same time as you declare them
  • Initialize the variables later and let Kotlin know that (this is the lateinit keyword)

Those 3 options are not equivalent, and depending on your code, the two first ones may be more appropriate than the third one.

lateinit will make your app crash if you access the variables before they are actually initialized.

like image 171
Vincent Mimoun-Prat Avatar answered Sep 22 '22 17:09

Vincent Mimoun-Prat


The init blocks are not functions, just remove the private fun part and the parentheses:

internal var background: Drawable
internal var xMark: Drawable

init {
    background = ColorDrawable(Color.RED)
    xMark = ContextCompat.getDrawable(this@Subscriptions_main, R.drawable.delete)
}
like image 44
hotkey Avatar answered Sep 25 '22 17:09

hotkey