cluster1
cluster1

Reputation: 5664

Syntax of secondary constructors in Kotlin

I've got this code-snippet. It shall demonstrate the order, in which constructors are executed:

fun main(args: Array<String>) {
    Sample("T","U")
}

class Sample(private var s : String) {
    constructor(t: String, u: String) : this(t) { // I don't get what "this(t)" is!
        this.s += u
    }
    init {
        s += "B"
    }
}

What's the ": this(t)" in the declaration of the secondary constructor?

That isn't the return-type? Isn't it?

Upvotes: 3

Views: 65

Answers (3)

alexrnov
alexrnov

Reputation: 2534

In addition to the answers. This is a required invocation to the default primary constructor:

class Sample(private var s: String) { }

Like in Java:

public Sample(String s) {

}

public Sample(String t, String u) {
    this(t); // invoke constructor Sample(String s)
}

To avoid this invocation, you can write like this:

class Sample {

    private var s = ""

    constructor(t: String) {
        s = ...
    }

    constructor(t: String, u: String) {
        s = ...
    }
}

Upvotes: 2

Yevhen Danchenko
Yevhen Danchenko

Reputation: 1099

In this particular case this is a keyword that delegates to the primary constructor. It is mandatory in Kotlin when your class has several ones. The Java equivalent would be:

class Simple {
  private String s;
  public Simple(String s) { // Here is your primary constructor
     this.s = s;
  }
  public Simple(String t, String u) { // Here is your secondary constructor 
     this(t);
     this.s += u;
  }
  {
     s += "B"; // Here is the init block
  }
}

Upvotes: 4

finebel
finebel

Reputation: 2355

With

this(t)

you call the primary constructor and passes t as an argument for s. Instead you could even write something like this:

this(s = "a")

Then you set s to "a". So the order is: Primary constructor, init, secondary constructor. For more detail: https://kotlinlang.org/docs/reference/classes.html

Upvotes: 2

Related Questions