Why each secondary constructor needs to delegate to the primary constructor in Kotlin?

前端 未结 1 449
清歌不尽
清歌不尽 2021-01-20 12:36

As kotlin reference Classes and Inheritance say,

If the class has a primary constructor, each secondary constructor needs to delegate to the primary

1条回答
  •  被撕碎了的回忆
    2021-01-20 12:56

    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.

    0 讨论(0)
提交回复
热议问题