How do I pass a function as a parameter in EK9?
← Functions and Methods · Ref: Q942
EK9 supports first-class functions. Define an abstract function as the parameter type, then pass a concrete function that matches its signature.
DEFINE THE FUNCTION TYPE
An abstract function acts as a type signature:
Transformer() as pure abstract -> incoming as Integer <- rtn as Integer
ACCEPT IT AS A PARAMETER
applyTransform()
->
value as Integer
fn as Transformer
<- answer as Integer: fn(value)
PASS A MATCHING FUNCTION
doubleIt() is Transformer as pure -> incoming as Integer <- rtn as Integer: incoming * 2
answer <- applyTransform(5, doubleIt)
The concrete function must match the abstract function's signature exactly. If it does not, the compiler raises E07480.
STREAMS USE THIS PATTERN
Stream operations like 'filter by' and 'map with' accept function parameters internally. The predicate you pass to filter must match the expected signature.
See Q597 for function parameters. See Q601 for dynamic functions. See Q596 for function vs method.
Example
defines module qa.functions.asparameter defines function Transformer() as pure abstract -> incoming as Integer <- rtn as Integer? doubleIt() is Transformer as pure -> incoming as Integer <- rtn as Integer: incoming * 2 tripleIt() is Transformer as pure -> incoming as Integer <- rtn as Integer: incoming * 3 applyTransform() -> operand as Integer fn as Transformer <- answer as Integer: fn(operand) defines program FunctionParamDemo() stdout <- Stdout() doubled <- applyTransform(7, doubleIt) stdout.println(`7 doubled: ${doubled}`) tripled <- applyTransform(7, tripleIt) stdout.println(`7 tripled: ${tripled}`)
Common mistakes
E06270 — Function parameters expect a matching function delegate, not a String literal — pass the function name (doubleIt) without quotes so the argument types match. See ek9 -h E06270 for details.
Incorrect:
applyTransform(7, "doubleIt")
Correct:
applyTransform(7, doubleIt)
Other ways to ask this
- What triggers E07480 FUNCTION_DELEGATE_EXPECTED in EK9?
- Can functions be first-class values in EK9?
- How do I use higher-order functions in EK9?
Coming from another language?
Java: Functional interfaces (Function, Predicate, Consumer). Python: functions are objects, pass directly. Rust: Fn/FnMut/FnOnce trait bounds. Go: func types as parameters. Kotlin: lambda and function references. EK9: abstract functions as type signatures, concrete functions with 'is' relationship.
Keywords: delegate, E07480, abstract, pass, higher-order, first-class, parameter, function