Condition chains

Syntax

	$value -> switch { 
   $condition1: $expr1;
   ...
   $conditionN: $exprN; 
   default: $exprDefault;
}

switch ($value) { 
   $pattern1: $expr1;
   ...
   $patternN: $exprN; 
   default: $exprDefault;
}

Description

If a value must be determined over several case distinctions, the nesting of several if-conditions leads to script that is difficult to read. Instead, a condition chain can be defined using switch.

The value of such a condition chain is the evaluation of the first expression exprX, whose condition conditionX evaluates to true. If all conditions conditionX evaluate to false, the final result is the evaluation of exprDefault. The default branch of the chain can be omitted. In this case, the value of the total expression is null, if all conditions evaluate to false.

If all conditions consist of an equality test, the pattern notation can be used. In this form, the chain of conditions evaluates to the expression exprX with smallest X whose pattern patternX is equal to the value of the evaluation of value.

The following examples are equivalent:

x -> switch { 
  $x == 1: "one"; 
  $x == 2: "a group"; 
  $x >= 3: "a crowd"; 
  default: "unknown";
}
x -> switch ($x) {
  1: "one"; 
  2: "two"; 
  3: "three"; 
  default: "unknown";
}

Parameter

Name Type Description Mandatory Default
value Number/string/boolean/buiness object/set A value to pass to the switch function to make case distinctions. yes
condition boolean A condition that will be checked for value. One of the two must be defined.
pattern Number/string/boolean/buisness object/set. A pattern that is directly compared to the evaluation of value. May shorten the write time for switch if this only checks for equality.
expr Number/string/boolean/buisness object/set An expression to evaluate if the associated condition or pattern results in true. yes

Return value

Type: Number/string/boolean/business object/set

The evaluation of the expr selected in the case distinction.

Examples

Pattern

	(x -> switch { 
  $x == 1: "one"; 
  $x == 2: "a group"; 
  $x >= 3: "a crowd"; 
  default: "unknown";
})(1)

Output: one

Conditions

	(x -> switch { 
  $x < 12: "child"; 
  $x < 18: "teen"; 
  $x < 70: "adult"; 
  default: "senior";
})(16)

Output: teen

More complex data types

{
  calendar = date(2021, 9, 7).toSystemCalendar();
  mySwitch = x -> switch ($x) { 
    "add day": $calendar.withDayAdded(1).toDate(); 
    "add month": $calendar.withMonthAdded(1).toDate(); 
    "add year": $calendar.withYearAdded(1).toDate();
  };
  $mySwitch("add month");
}

Output: 07.11.2021