Create a dynamic class with multiple methods implementing a trait inline.
← Advanced Type System · Ref: Q1127
Override multiple abstract methods in a dynamic class:
obj <- () with trait of Speaker as class override greet() as pure <- rtn as String: "Hello" override farewell() as pure <- rtn as String: "Goodbye" default operator ?
Every abstract method in the trait must be overridden in the dynamic class body.
See Q1125 for dynamic functions. See Q1126 for dynamic class with capture.
Example
#!ek9 defines module qa.advancedtypes.dynamicclassmethods defines trait Speaker greet() as pure abstract <- rtn as String? farewell() as pure abstract <- rtn as String? defines program DynamicClassMethodsDemo() stdout <- Stdout() speaker <- () with trait of Speaker as class override greet() as pure <- rtn as String: "Hello" override farewell() as pure <- rtn as String: "Goodbye" default operator ? stdout.println(speaker.greet()) stdout.println(speaker.farewell())
Common mistakes
E01075 — EK9 has no 'new' keyword — instantiate a type by calling its constructor directly, e.g. Stdout(). See ek9 -h E01075 for details.
Incorrect:
stdout <- new Stdout()
Correct:
stdout <- Stdout()
Other ways to ask this
- I need an inline class that implements two abstract methods from a trait
- In Java I'd use an anonymous class with multiple method overrides. Write the EK9 way
- Given a trait with greet() and farewell(), create a one-off inline implementation
- Build a dynamic class that overrides multiple trait methods
Coming from another language?
Java: anonymous inner class with multiple method overrides. Kotlin: object expression. Python: lambda (single method only). EK9: dynamic class implementing full trait.
Keywords: class, dynamic, inline, methods, multiple, trait