I think I've read somewhere that this is possible.
Use case
I want to create a trait that when mixed in memoizes the hashCode by overwriting the method and storing the r开发者_JS百科esult of the overwritten method in a val.
trait MemoHashCode {
val hashCode = callToOverwritten_hashCode
}
Simply use the super
keyword:
trait MemoHashCode {
val hashCode = super.hashCode
}
That is possible because every trait implicitly extends AnyRef
which has hashCode
defined.
If you want to use methods not defined on every object you would have to make sure that the trait can only be mixed in with objects that have the method implemented which you are going to use. That is possible via a self type annotation:
trait MemoSomethingElse {
this: SomeType => // SomeType has method somethingElse
val somethingElse = super.somethingElse
}
精彩评论