39 Switch results
switch can produce a result while extracting an enum variant's payload.
norm
enum Result {
Success(Integer count),
Failure(String reason)
}
String describe(Result result) {
return switch result {
case Success(Integer count) { break "${count} items" }
case Failure(String reason) { break reason }
}
}
main() {
printLine(describe(result: Result.Success(count: 3)))
printLine(describe(result: Result.Failure(reason: "empty")))
}Expected output:
text
3 items
emptyEach case binds the matching payload and exits with break followed by a string. The function returns that switch result; a statement switch would not need a result value.
Try it: Change the Success branch to include a label before the count.
Precise rules: Reference.