Create a dynamic class that implements a Describable trait inline.
← Advanced Type System · Ref: Q1126
Create a dynamic class implementing a trait inline:
myObj <- (label) with trait of Describable as class override describe() as pure <- rtn as String: label default operator ?
(label) captures the local variable. The dynamic class implements the trait's abstract methods -- no named class needed.
See Q1125 for dynamic functions. See Q1129 for trait delegation.
Example
defines module qa.advancedtypes.dynamicclasstrait defines trait Describable describe() as pure abstract <- rtn as String? defines program DynamicClassTraitDemo() stdout <- Stdout() label <- "Dynamic" //Create inline implementation of Describable myDescribable <- (label) with trait of Describable as class override describe() as pure <- rtn as String: label default operator ? stdout.println(myDescribable.describe())
Common mistakes
E01075 — EK9 has no 'new' keyword - create an inline implementation with '(captures) with trait of TraitName as class'. See ek9 -h E01075 for details.
Incorrect:
myDescribable <- new Describable()
Correct:
myDescribable <- (label) with trait of Describable as class override describe() as pure <- rtn as String: label default operator ?
Other ways to ask this
- I need an anonymous class implementing a trait, created inline with captured state
- In Java I'd use an anonymous inner class. Write the EK9 dynamic class equivalent
- Given a Describable trait, create an inline implementation that captures a label variable
- Build a one-off trait implementation without defining a named class
Coming from another language?
Java: new Describable() { @Override String describe() { return label; } }. Kotlin: object : Describable { }. EK9: (captures) with trait of X as class.
Keywords: inline, dynamic, trait, class, anonymous, capture