12

Kotlin variable initialization for child class behaves weird for initializing va...

 4 years ago
source link: https://stackoverflow.com/questions/59822125/kotlin-variable-initialization-for-child-class-behaves-weird-for-initializing-va
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Kotlin variable initialization for child class behaves weird for initializing variable with value 0

I have created the following class hierarchy:

open class A {
    init {
        f()
    }

    open fun f() {
        println("In A f")
    }
}

class B : A() {
    var x: Int = 33

    init {
        println("x: " + x)
    }

    override fun f() {
        x = 1
        println("x in f: "+ x)
    }

    init {
        println("x2: " + x)
    }
}

fun main() {
    println("Hello World!!")
    val b = B()
    println("in main x : " + b.x)
}

The output of this code is

Hello World!!
x in f: 1
x: 33
x2: 33
in main x : 33

But if I change the initialization of x from

var x: Int = 33
var x: Int = 0

the output shows the invocation of the method in contrast to the output above:

Hello World!!
x in f: 1
x: 1
x2: 1
in main x : 1

Does anyone know why the initialization with 0 causes a different behaviour than the one with another value?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK