Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing overridden methods from a mixin in Scala

Tags:

scala

traits

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 result of the overwritten method in a val.

trait MemoHashCode {
  val hashCode = callToOverwritten_hashCode
}
like image 627
ziggystar Avatar asked Jan 20 '23 23:01

ziggystar


1 Answers

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
}
like image 57
Martin Ring Avatar answered Jan 28 '23 20:01

Martin Ring