Traits and abstract methods override in Scala

后端 未结 1 1373
遇见更好的自我
遇见更好的自我 2021-01-29 23:53

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

1条回答
  •  -上瘾入骨i
    2021-01-30 00:27

    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
    

    0 讨论(0)
提交回复
热议问题