Reputation: 9698
It's obvious that this doesn't work:
trait A
val a = new A
since traits cannot be instantiated (if we added {}
after new A
then it would work, since we're creating an anonymous class).
However, this does work, and I don't know why:
trait A
trait B
val a = new A with B
Does the process of linearization automatically create an anonymous class for a base trait or what?
Upvotes: 2
Views: 60
Reputation: 139028
From section 5.1 of the spec:
It is possible to write a list of parents that starts with a trait reference, e.g.
mt1 with ... with mtn
. In that case the list of parents is implicitly extended to include the supertype ofmt1
as first parent type. The new supertype must have at least one constructor that does not take parameters.
So when you write new A with B
and A
is a trait, you're actually getting new AnyRef with A with B
. I'm not 100% sure why the same transformation isn't applied to new MyTrait
, but I'd guess it has something to do with avoiding confusion between traits and classes.
Upvotes: 4