I saw some code write trait as following:
trait SelfAware { self: Self =>
....
}
class Self
val s = new Self with SelfAware // this is ok
println(s.self) // error happened
class X
new X with SelfAware // error happened here
I’d like to know why the error happened and how to use trait in this way?
The error is occurring because you have constrained the type of the
thisreference (which you have namedself) to be of typeSelf. When you saynew Self with SelfAware, this is OK, because that object is of typeSelflike you asked. But when you saynew X with SelfAware, there is no evidence thatXis in any way a subtype ofSelf.In your new object of type
X with SelfAware, what would be the type of itsselfmember? Well, it would not be of typeSelf, but of typeX. But you have defined the traitSelfAwareso thatselfmust be of typeSelf, so you get a type error.