Skip to content

32 Fluent methods ​

A method may return this so the caller can continue operating on the same object.

norm
class Counter {
  Integer value

  Counter add(Integer amount) {
    value = value + amount
    return this
  }
}

main() {
  Counter counter = Counter(value: 1)
  counter.add(amount: 2).add(amount: 3)
  printLine(counter.value)
}

Expected output:

text
6

Each add changes the counter, then returns that very counter. The second call therefore receives the first call's result; the final value includes both additions.

Try it: Split the chain into two statements and check the same output.

Precise rules: Reference.

Norm 0.25