Create a dynamic function that captures a greeting and prepends it to any input.
← Advanced Type System · Ref: Q1181
Define an abstract function type, then extend it dynamically:
Greeter as abstract -> name as String <- message as String?
greet <- (greeting: greetingText) extends Greeter as function message: `${greeting} ${name}`
Use 'as abstract' on the function definition. Dynamic functions use 'extends TypeName as function'. Named capture (greeting: greetingText) copies greetingText into field 'greeting'.
See Q1125 for dynamic function capture. See Q1126 for dynamic classes.
Example
defines module qa.advancedtypes.dynamicfunctioncorrect defines function Greeter as abstract -> name as String <- message as String? defines program DynamicFunctionCorrectDemo() stdout <- Stdout() greetingText <- "Hello" //Create dynamic function with named capture greet <- (greeting: greetingText) extends Greeter as function message: `${greeting} ${name}` stdout.println(greet("Alice")) stdout.println(greet("Bob")) //Another dynamic function with different captured state farewellText <- "Goodbye" farewell <- (farewell: farewellText) extends Greeter as function message: `${farewell} ${name}` stdout.println(farewell("Charlie"))
Other ways to ask this
- Write code for a closure that captures a local variable as state
- I need a dynamic function extending an abstract function type with named capture
- In JavaScript I'd use a closure over a variable. Write the EK9 dynamic function equivalent
- Build a Greeter dynamic function that captures a greeting string and prepends it to input
Coming from another language?
JavaScript: const greet = (name) => greeting + name (closure). Java: Function<String,String> greet = name -> greeting + name. Python: lambda name: greeting + name. EK9: (field: source) extends AbstractType as function.
Keywords: function, greeting, capture, extends, closure, abstract, dynamic