when Expressions

A large part of computer programming is performing an action when a pattern matches.

Anything that makes this task easier is a boon for programmers. Kotlin provides language support in the form of when expressions.

A when expression compares a value against a selection of possibilities. It begins with the keyword when and the value you want to compare inside parentheses. This is followed by a body containing a set of possible matches and their associated actions. Each match is an expression followed by a right arrow ->. The arrow is the two separate characters - and > with no white space between them. The expression is evaluated and compared to the target value. If it matches, the expression to the right of the -> produces the result of the when expression.

End of sample. See AtomicKotlin.com for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.