How do I assign a value based on a condition in EK9?
← Control Flow · Ref: Q984
EK9 provides three patterns for conditional value assignment:
PATTERN 1: IF/ELSE ASSIGNMENT
label <- "standard" if score > threshold label := "premium"
PATTERN 2: SWITCH EXPRESSION
category <- switch rating <- rtn as String? case > highMark rtn: "excellent" case > passMark rtn: "good" default rtn: "needs improvement"
PATTERN 3: COALESCING (?? and :=?)
displayName <- userName ?? "Guest" fallback :=? computeDefault()
Choose if/else for simple binary conditions. Choose switch expression for multiple cases. Choose ?? or :=? when providing defaults for unset values.
Example
defines module qa.controlflow.conditionalvalue defines function classifyTemperature() as pure -> celsius as Float <- rtn as String? coldThreshold <- 10.0 hotThreshold <- 30.0 rtn: switch celsius <- category as String? case < coldThreshold category: "cold" case > hotThreshold category: "hot" default category: "mild" defines program ConditionalValueDemo() stdout <- Stdout() // Pattern 1: if/else assignment temperature <- classifyTemperature(15.0) descriptor <- "unknown" if temperature? descriptor := temperature stdout.println(`Descriptor: ${descriptor}`) // Pattern 2: switch expression weather <- classifyTemperature(22.0) stdout.println(`Weather: ${weather}`) // Pattern 3: coalescing for defaults nickname <- String() displayName <- nickname ?? "Anonymous" stdout.println(`Name: ${displayName}`)
Common mistakes
E01010 — The ? in EK9 is the isSet suffix operator, not a conditional expression. This line does not parse. Use if/else assignment instead.
Incorrect:
descriptor <- temperature? ? temperature : "unknown"
Correct:
descriptor <- "unknown" if temperature? descriptor := temperature
E01010 — EK9 does not have an inline if expression. Use a function call with a guard, or if/else assignment on separate lines.
Incorrect:
weather <- if classifyTemperature(22.0) then classifyTemperature(22.0) else "unknown"
Correct:
weather <- classifyTemperature(22.0)
Other ways to ask this
- How do I choose between two values based on a condition in EK9?
- What replaces conditional value assignment in EK9?
- How do I write a one-line conditional in EK9?
- How do I assign different values depending on a test?
Coming from another language?
Other languages use a conditional expression for this. EK9 uses if/else assignment, switch expressions, or the ?? coalescing operator depending on the scenario.
Keywords: value, switch expression, if else, assign, choose, conditional