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?
Before using lateinit
, you must understand what that means.
Your variables are not initialized properly. Various ways to solve that problem:
init
block (not a private function as you declared it)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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With