-
Notifications
You must be signed in to change notification settings - Fork 0
Function: when if match switch
Maciej Górski edited this page Jan 6, 2016
·
2 revisions
function when(
condition0: ()->boolean, block0: ()->anything,
[condition1: ()->boolean, block1: ()->anything,
[condition2: ()->boolean, block2: ()->anything,
[...]]]
blockElse: ()->anything = {}
)->anything
When blockElse is not given, this always returns nothing (empty collection of returned values), so it works like if (condition0) block0() else if (condition1) block1() in imperative languages.
When called with blockElse, returned type is inferred (when possible), e.g. in
value = when(condition0 = { false }, block0 = { 0 }, blockElse = { 1 })
value is of type numeric.
When one or more functions return more than one thing, when selects as many values to return as possible, e.g.
value1 is return0, value2 is return1 = when(
condition0 = { false }, block0 = { true, 1, "string" },
condition1 = { true }, block1 = { "sth", false, {}, dictionary("a" to 1, "b" to 2) },
blockElse = { [0, 1], false, "else" }
)
You could skip returned value. See Multiple return values for more details.
When in doubt, i.e. returned value(s) cannot be inferred, you need to specify which is used.
Given partition function, which returns two lists:
partition(list: numericList, predicate: (numeric)->boolean) -> (matching: numericList, nonmatching: numericList)
value = when(
condition0 = { true }, block0 = {
x is nonmatching = partition([0, 1, 2, 4], { it -> it % 2 == 0 })
x
},
blockElse = { [6, 6, 6] }
)