Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

kotlin parent class has var that depend on abstract var

class C(val string: String) {
    init {
        println(string)
    }
}
abstract class A {
  abstract var string: String  
  val c = C(string)
}
class B : A() {
    override var string = "string"
}


fun main() {
    B()
}

kotlin playground for the problem

This code crash in runtime due to string var not initialized, how to do it right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s not a good practice and dangerous to use an abstract or open variable in the initialization of your class. And if you write this code in Android Studio or IntelliJ IDEA you will get this warning: Accessing non-final property string in constructor.

So what’s happening here ? Well the super class which is A is going to be initialized first before totally initializing B, so this line of code val c = C(string) is going to run before even giving a value to string and that’s what causing the error and you will get a NullPointerException because string is null.

How to fix this ? You can use lazy to initialize c like that:

val c by lazy { C(string) }

Now c is not going to be initialized only if you call it, so now it’s safe
because you can’t call it only if B is fully initialized.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading