Skip to content

11 if as a result ​

An if/else expression can produce one value from either branch.

norm
String nextStep(Boolean ready) {
  return if ready {
    "run the tests"
  } else {
    "finish the code"
  }
}

main() {
  printLine(nextStep(true))
  printLine(nextStep(false))
}

Output:

text
run the tests
finish the code

Each branch's final expression is a String, so the whole if has type String and can be returned. When a result is required, both paths must produce compatible values; an absent else would leave one path without a result.

Try it: Change one branch to an Integer and inspect how the result type is checked.

Precise rules: Language Reference.

Norm 0.25