2

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?

1 Answer 1

4

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 of mt1 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what my hunch was, but your reference to the spec cleared off any doubts. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.