How does EK9 handle return values without a return statement?
← Classes and OOP · Ref: Q878
Look at this function — notice there is no 'return' keyword anywhere:
maxOfTwo() as pure -> firstNum as Integer, secondNum as Integer <- rtn as Integer: firstNum if secondNum > firstNum rtn: secondNum
The '<- rtn as Integer: firstNum' line DECLARES the return variable and gives it an initial value. The compiler then checks that ALL possible code paths leave 'rtn' with a valid value. If any path could leave it uninitialised, the code won't compile.
This design eliminates an entire category of bugs: forgotten returns, early returns bypassing cleanup, and unreachable code after return. The 'return' keyword simply does not exist in EK9's grammar.
See Q146 for the design rationale. See Q144 for no break/continue/return.
Example
defines module qa.classes.no.return defines function maxOfTwo() as pure -> firstNum as Integer secondNum as Integer <- rtn as Integer: firstNum //All paths must set rtn — compiler enforces this if secondNum > firstNum rtn: secondNum defines class Formatter prefix <- "[" suffix <- "]" default Formatter() Formatter() -> p as String s as String prefix :=: p suffix :=: s format() -> text as String <- rtn as String: `${prefix}${text}${suffix}` default operator ? defines program ReturnDemo() stdout <- Stdout() bigger <- maxOfTwo(10, 20) stdout.println(`Max: ${bigger}`) formatter <- Formatter("<", ">") if formatter? stdout.println(formatter.format("hello"))
Other ways to ask this
- Why doesn't EK9 have a return keyword?
- How do I return a value from a function in EK9?
- What is the '<-' return declaration in EK9?
Coming from another language?
Java: return keyword required. Python: return keyword. Go: return keyword. EK9: '<-' declares return variable, no return statement exists.
Keywords: flow, declaration, return, no-return, variable, arrow, initialise