Why "trait T; class C; class X extends (C with T)` cannot be compiled? "
I'm having a hard time structuring my answer in a pleasant manner, but here's an attempt to explain what's going on nonetheless:
You get a compilation error because the proposal extends
requires a class and traits, not types, and you are giving a type. Classes and traits should not be confused with types.
There are, of course, better explanations for this. But basically, a type indicates operations that can be applied to something (and sometimes other properties). Classes and traits define the behavior of their instances.
In most statically typed OO languages, every class / interface / property also has an associated type. However, the mutual meaning is usually wrong: not all types have a corresponding class / interface / trait. For example, yours C with T
is a type, but not a class or a trait (or even a combination of both).
extends
Classes and traits (separated by a character with
) are expected in sentences , but not one type. This has to do with what it extends
means: extending the behavior of that thing. As I said, types don't define behavior.
In most cases, the syntax A with B
represents a type, which is a subtype of a type A
and a type B
. However, it extends
with
accepts a different meaning in the clause and simply acts as a separator for arguments extends
(just as it ,
acts as a separator for method invocation arguments).
If you write class X extends C with T
it will work, because it means class X extends C, T
if you want.
NTN
source to share