Is it possible to call an overridden method from self type?

后端 未结 3 638
独厮守ぢ
独厮守ぢ 2021-01-07 23:32

Consider this:

 class Foo { def foo = \"foo\" }
 trait Bar { self: Foo =>
    override def foo = \"bar\"
 }

I was pleasantly surprised

3条回答
  •  感动是毒
    2021-01-08 00:33

    I am not aware of any particular syntax to disentangle the base class and the mixed-in trait. There is, however, an easy solution to achieve the result manually by distinguishing the overridden method from the default implementation in the base class:

    class Foo { def foo = defaultFoo; def defaultFoo = "foo" }
    trait Bar { self: Foo => override def foo = self.defaultFoo + "bar" }
    

    As expected

    new Foo with Bar foo == "foobar"
    new Foo foo == "foo"
    

提交回复
热议问题