Write a function that returns a set or unset String depending on input.
← Functions and Methods · Ref: Q1167
String() creates an unset return; caller guards with ?:
<- colour as String: String() if name == "sky" colour: "blue"
If the condition doesn't match, the return stays unset. Caller uses if-guard: if found <- findColour("sky"). See Q1146, Q1088.
Example
defines module qa.functionsandmethods.functionoptionalreturn defines function findColour() as pure -> name as String <- colour as String: String() if name == "sky" colour: "blue" else if name == "grass" colour: "green" defines program FunctionOptionalReturnDemo() stdout <- Stdout() //Found: the guard sets the variable and runs the block. Not found: the return is unset, so the else runs for colourName in ["sky", "ocean"] if found <- findColour(colourName) stdout.println(`Found ${colourName}: ${found}`) else stdout.println(`No colour found for ${colourName}`)
Common mistakes
E08180 — A return variable must be initialised (or declared with ?). The return here has no initialiser. Optional is a valid type, but the simpler EK9 idiom is to initialise with an unset String() and let the caller guard with ?. See ek9 -h E08180 for details.
Incorrect:
<- colour as Optional of String
Correct:
<- colour as String: String()
Other ways to ask this
- I need a function that sometimes returns a value and sometimes returns nothing
- In Java I'd return Optional<String>. Write the EK9 function with optional return
- Given a lookup function, return the found value or leave the return unset
- Create a function whose return can be checked with ? by the caller
Coming from another language?
Java: Optional<String>. Kotlin: String?. Rust: Option<String>. EK9: return String() (unset) or a value — caller uses ? or guard.
Keywords: function, optional, lookup, unset, return, guard