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?
Self-types are a way to declare that a trait must be mixed into another trait, even though it doesn't directly extend it. That makes the members of the dependency available without imports. A self-type is a way to narrow the type of this or another identifier that aliases this .
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.
A Trait is a concept pre-dominantly used in object-oriented programming, which can extend the functionality of a class using a set of methods. Traits are similar in spirit to interfaces in Java programming language. Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters.
In scala, trait mixins means you can extend any number of traits with a class or abstract class. You can extend only traits or combination of traits and class or traits and abstract class. It is necessary to maintain order of mixins otherwise compiler throws an error.
The error is occurring because you have constrained the type of the this
reference (which you have named self
) to be of type Self
. When you say new Self with SelfAware
, this is OK, because that object is of type Self
like you asked. But when you say new X with SelfAware
, there is no evidence that X
is in any way a subtype of Self
.
In your new object of type X with SelfAware
, what would be the type of its self
member? Well, it would not be of type Self
, but of type X
. But you have defined the trait SelfAware
so that self
must be of type Self
, so you get a type error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With