Why can't I use compound assignment like '+=' in a switch pre-flow in EK9?
← Control Flow · Ref: Q836
A switch pre-flow written WITHOUT a separate control expression must assign to a simple variable, and that variable becomes the subject of the switch ('switch result += 3' switches on result). A compound assignment on a property access such as 'scoring.prop1 += 3' has no variable to be the subject, so the compiler reports E07340 ('failed to find subject of flow'). Declare a variable and name it as the control: 'switch controlScore <- scoring.prop1 + 3 with controlScore'.
See Q69 for multi-case switch. See Q144 for no break/continue/return.
Example
defines module qa.controlflow.switch.preflow defines record Scoring prop1 <- 0 Scoring() -> initial as Integer prop1 :=: initial override operator ? as pure <- rtn as Boolean: prop1? defines function classifyScore() <- rtn as String: String() scoring <- Scoring(5) result <- 0 switch controlScore <- scoring.prop1 + 3 with controlScore case > 1 result += 6 default result += 10 rtn: $result defines program SwitchPreFlowDemo() stdout <- Stdout() stdout.println(classifyScore())
Common mistakes
E07340 — A compound assignment on a property in switch pre-flow gives the switch no variable subject (E07340). Declare a variable and name it with 'with' instead. See ek9 -h E07340 for details.
Incorrect:
switch scoring.prop1 += 3
Correct:
switch controlScore <- scoring.prop1 + 3 with controlScore
Other ways to ask this
- What is E07340 PRE_FLOW_SYMBOL_NOT_RESOLVED?
- Why does 'switch record.prop += 3' fail in EK9?
- What assignment forms are valid in switch pre-flow?
Coming from another language?
Java: switch has no pre-flow. C: assignment in switch is bad practice. Kotlin: when has no pre-flow. EK9: a pre-flow with no separate control must assign to a simple variable (the subject); property targets need a declaration plus 'with'.
Keywords: switch, pre-flow, assignment, declaration, compound, E07340