Thursday, October 31, 2013

Self Type in Trait

Self type can be used in Trait to make sure the classes that mix in this trait contain the reference to the object of type declared as a self reference in the Trait.

Is it so confusing, let me explain with a simple example,

trait A {
def print(message: String) = println(message)
}

class B {
self: A=>
}

the above class B declares the trait A as self type. The fields and methods of the trait can be used in the class B only if A is mixed in while B is instantiated.

val instance1 = new B with A    ---> CORRECT

val instance2 = new B ---> ERROR: class B cannot be instantiated because it does not conform to its self-type B with A


More examples,

class C extends B {                    ----> WRONG. because self type of B is not mixed in here.
}

class C extends B with A {        ----> CORRECT
}

class D extends B {
self: A =>                                   ----> CORRECT
}

No comments:

Post a Comment