Changhyun Eun
Changhyun Eun

Reputation: 559

Kotlin constructor (primary constructor)

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??

Upvotes: 0

Views: 699

Answers (1)

tynn
tynn

Reputation: 39873

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:

Upvotes: 6

Related Questions