How to call super method when overriding a method through a trait

后端 未结 3 1942
南笙
南笙 2020-12-29 06:19

It would appear that it is possible to change the implementation of a method on a class with a trait such as follows:

trait Abstract { self: Result =>
            


        
3条回答
  •  借酒劲吻你
    2020-12-29 06:51

    abstract override is the mechanism, aka stackable traits. It's worth adding that linearization counts, because that's what determines what super means.

    This question is a great addendum to the canonical Q&A on self-type vs extension.

    Where the inheritance is ambiguous with self-types:

    scala> trait Bar { def f: String = "bar" }
    defined trait Bar
    
    scala> trait Foo { _: Bar => override def f = "foo" }
    defined trait Foo
    
    scala> new Foo with Bar { }
    :44: error: <$anon: Foo with Bar> inherits conflicting members:
      method f in trait Foo of type => String  and
      method f in trait Bar of type => String
    (Note: this can be resolved by declaring an override in <$anon: Foo with Bar>.)
                  new Foo with Bar { }
                      ^
    

    Then obviously, you can choose:

    scala> new Foo with Bar { override def f = super.f }
    res5: Foo with Bar = $anon$1@57a68215
    
    scala> .f
    res6: String = bar
    
    scala> new Foo with Bar { override def f = super[Foo].f }
    res7: Foo with Bar = $anon$1@17c40621
    
    scala> .f
    res8: String = foo
    

    or

    scala> new Bar with Foo {}
    res9: Bar with Foo = $anon$1@374d9299
    
    scala> .f
    res10: String = foo
    

提交回复
热议问题