https://kotlinlang.org logo
#announcements
Title
# announcements
g

Guy Bieber

03/11/2020, 6:12 PM
I have a parent class in java that calls an overrided get method in a child class during construction. The child class returns a null object from the get method because the parent class is initialized prior to the child class. Is there a good workaround for this? Example Code:
Copy code
abstract class Parent {

    init {
        print("Parent Init: ")
        var str = getString()
        println("  $str")
    }
    constructor () {
        print("Parent Constructor:  ")
        var str = getString()
        println("  $str")
    }

    protected abstract fun getString () : String

}

class Child : Parent {

    var myString : String = "test"
    init {
        print("Child Init:  ")
        var str = getString()
        println("$str")
    }
    constructor () {
        print("Child Constructor:  ")
        var str = getString()
        println("$str")
    }

    override fun getString() : String {
        return myString
    }

}

var child : Child = Child()
println("Main: ${child.myString}")
Example output
Copy code
Parent Init:   null
Parent Constructor:    null
Child Init:  test
Child Constructor:  test
Main: test
a

araqnid

03/11/2020, 7:15 PM
No, and this is an issue in Java too. We usually avoid calling instance methods in constructors for this reason. If the string is something class-level rather than instance-level, it could go in a companion object which gets passed to the parent constructor
2
r

Russ Tennant

03/11/2020, 7:27 PM
To add to what Steve wrote, It is error prone to call non-final instance methods during initialization. I’d recommend you redesign your API to not do it. Intellij has an inspection called “‘this’ reference escaped in object construction” to check just for this type of issue.
From the inspection description:
Copy code
Reports possible escapes of this during object construction. Escapes occur when this is used as a method argument or the object of an assignment in a constructor or initializer. Such escapes may result in subtle bugs, as the object is now available in a context in which it is not guaranteed to be initialized.
g

Guy Bieber

03/11/2020, 8:08 PM
It’s coming from a library I’m using. Nordic ble
The string example was to simplify.
r

Russ Tennant

03/11/2020, 8:10 PM
In that case, you’ll have to be very careful in how you write the code since you’ll be interacting with a partially constructed object.
g

Guy Bieber

03/11/2020, 8:13 PM
I have a fix with a companion class for the simple case however it is a callback class that needs access to parent class methods and variables.