开发者

Accessing overridden methods from a mixin in Scala

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜