Pass a dynamic class as a function argument.
← Advanced Type System · Ref: Q1128
Pass a dynamic class to a function as the trait type:
myObj <- (label) with trait of Describable as class override describe() as pure <- rtn as String: label default operator ? printDescription(myObj)
The function receives it as Describable -- it does not know or care that it is a dynamic class.
See Q1126 for dynamic class basics. See Q1125 for dynamic functions.
Example
defines module qa.advancedtypes.dynamicclassasargument defines trait Describable describe() as pure abstract <- rtn as String? defines function printDescription() -> item as Describable <- output as String: item.describe() defines program DynamicClassAsArgumentDemo() stdout <- Stdout() label <- "Widget" //Create dynamic class implementing Describable widget <- (label) with trait of Describable as class override describe() as pure <- rtn as String: label default operator ? //Pass it to a function that takes the trait type result <- printDescription(widget) stdout.println(result)
Common mistakes
E01075 — EK9 has no 'new' keyword; instantiate a type directly as TypeName() (or build a dynamic class first and pass that). See ek9 -h E01075 for details.
Incorrect:
printDescription(new Describable())
Correct:
printDescription(widget)
Other ways to ask this
- I need to create an inline trait implementation and pass it to a function
- In Java I'd pass an anonymous class to a method. Write the EK9 equivalent
- Given a function that takes a Describable, create and pass a dynamic implementation
- Build a dynamic class inline at the call site and pass it directly
Coming from another language?
Java: printDescription(new Describable() { ... }). Kotlin: printDescription(object : Describable { ... }). EK9: create dynamic class, pass as trait type.
Keywords: argument, dynamic, class, pass, function, inline