Traits and abstract methods override in Scala

ScalaTraits

Scala Problem Overview


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.

Scala Solutions


Solution 1 - Scala

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIttayDView Question on Stackoverflow
Solution 1 - ScalaretronymView Answer on Stackoverflow