Self Type in Scala

abstract class A (val x: Int){
}
trait B {
    def xPlus1: Int = x +1
}

Of course this is silly. Because B does not know x defined in A, Scala compiler will complain,

error: not found: value x
       def xPlus1: Int = x +1

However, in many applications, we do know that trait B has to be mixed with a sub-type of A (e.g. Trait Calibration must be mix only with some Model in the context of statistics). In this case, we can explicitly tell the compiler through self type. In our toy example,

trait B {
self: A =>
    def xPlus1: Int = x+1
}

Now, we test this approach by creating a concrete class C as

scala> case class C(override val x:Int) extends A(x) with B
scala> C(10) xPlus1
res1: Int = 11
This entry was posted in Scala. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *