Skip to content

30 Explicit constructors ​

A class can replace implicit field construction with a same-named constructor.

norm
class Counter {
  Integer value

  Counter(Integer initial) {
    this.value = initial
  }
}

main() {
  Counter counter = Counter(initial: 7)
  printLine(counter.value)
}

Expected output:

text
7

Counter(Integer initial) has no return type. The constructor assigns the required field before the instance can be used, and the call labels its initial parameter.

Try it: Double initial in the constructor and predict the field value.

Precise rules: Reference.

Norm 0.25