Create a dynamic function that captures a prefix variable and prepends it to input.

← Advanced Type System · Ref: Q1125

Capture a variable into a dynamic function:

  transform <- (prefix: prefixText) extends Transformer as function
    output: `${prefix} ${input}`

(prefix: prefixText) captures local 'prefixText' into a field named 'prefix'. The abstract function type defines parameter and return types.

See Q1126 for dynamic classes.

Example

defines module qa.advancedtypes.dynamicfunctioncapture

  defines function

    Transformer as abstract
      -> input as String
      <- output as String?

  defines program

    DynamicFunctionCaptureDemo()
      stdout <- Stdout()
      prefixText <- "Hey"

      //Create dynamic function capturing prefixText as 'prefix'
      transform <- (prefix: prefixText) extends Transformer as function
        output: `${prefix} ${input}`

      result <- transform("World")
      stdout.println(result)

Common mistakes

E50001 — A capture list names an existing local variable: (prefix: prefixText) copies prefixText into a field called prefix. A misspelt variable such as prefixTxt is not resolved. Use 'extends TypeName as function' with a capture list.

Incorrect:

      transform <- (prefix: prefixTxt) extends Transformer as function

Correct:

      transform <- (prefix: prefixText) extends Transformer as function
Other ways to ask this
  • I need a closure that captures a local variable and uses it in its body
  • In JavaScript I'd create a closure over a variable. Write the EK9 dynamic function
  • Given a prefix string, create a dynamic function that adds it to any input
  • Build a function that captures state with named capture syntax
  • Create a dynamic function that captures a greeting and prepends it to any input.
  • 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 fn = (input) => prefix + input (closure). Java: lambda with effectively final variable. Python: lambda or closure. EK9: named capture in dynamic function.

Keywords: extends, function, greeting, capture, dynamic, abstract, lambda, state, closure