I have a base abstract class (trait). It has an abstract method foo()
. It is extended and implemented by several derived classes. I want to create a trait that can be mixed into the derived classes so that it implements foo()
and then calls the derived class's foo()
.
Something like:
trait Foo { def foo() } trait M extends Foo { override def foo() { println("M") super.foo() } } class FooImpl1 extends Foo { override def foo() { println("Impl") } } class FooImpl2 extends FooImpl1 with M
I tried self types and structural types, but I can't get it to work.
An abstract method is a method that is declared, but contains no implementation. you can override both abstract and normal methods inside an abstract class. only methods declared as final cannot be overridden.
Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance. Trait cannot have parameters in its constructors.
In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.
An abstract method is a contract which forces its immediate subclass to implement the behaviour of all abstract methods. Where as overriding is optional and is not always a necessity for the subclasses. Efficiency of abstract method lies in the fact that they force the immediate subclass to provide implementation.
You were very close. Add the abstract modifier to M.foo, and you have the 'Stackable Trait' pattern: http://www.artima.com/scalazine/articles/stackable_trait_pattern.html
trait Foo { def foo() } trait M extends Foo { abstract override def foo() {println("M"); super.foo()} } class FooImpl1 extends Foo { override def foo() {println("Impl")} } class FooImpl2 extends FooImpl1 with M
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With