Kotlin - Property must be initialized or be abstract even if there is an init() function
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.
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)
}