Kotlin constructor (primary constructor)

耗尽温柔 提交于 2020-07-16 10:25:18

问题


I have a question about Kotlin constructor.

class abc {
    constructor(a: Int)
    constructor(a: Int, e: Int)
}

class def(a: Int) {
    constructor(a: Int, e: Int) : this(a)
}

Why do I need to call this(a) in def class?

What is different between class abc and def??


回答1:


The first class doesn't have a primary constructor while the second class has one. Per the documentation for Secondary Constructors you then have to delegate to it.

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). Delegation to another constructor of the same class is done using the this keyword:



来源:https://stackoverflow.com/questions/47979047/kotlin-constructor-primary-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!