Why each secondary constructor needs to delegate t

2020-04-11 10:30发布

问题:

As kotlin reference Classes and Inheritance say,

If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s).

I can't understand why kotlin secondary constructor need do this? It is can be prevent some problems in Java?

回答1:

This is because init blocks and property initializers always need to run properly to construct an instance of a class, and they might rely on properties passed to the primary constructor to do their initialization - this is the convenience that the primary constructor gives you (as well as being able to have properties right in the header of the class).

As an example, take this class:

class Rectangle(val width: Int, val height: Int) {

    constructor(size: Int) : this(size, size)

    val area = width * height

    init {
        println("New rectangle, $width x $height")
    }

}

Both the area property and the init block make use of primary constructor parameters - if the secondary constructor didn't call through to the primary one, initialization couldn't be performed.

The width and height properties are also implicitly initialized when the primary constructor is called - again, if the secondary constructor didn't call the primary, these would be left uninitialized.

Of course, you can have multiple secondary constructors in a class if there's no primary constructor (this is common for Android Views for example) - you'll just have a harder time performing your initialization logic if there's any.



标签: kotlin