Why `trait T; class C; class X extends (C with T)`

2020-07-20 03:52发布

问题:

Scala code:

trait T
class C
type W = C with T
class X extends W

W is a type alias, but I want define a class to extend it. Why and how to fix it?

回答1:

I have difficulty structuring my answer in a nice way, but here is nevertheless an attempt at explaining what's going on:

You get a compilation error because the extends clause requires class and traits, not types, and you're giving a type. Classes and traits must not be confused with types.

There are certainly better explanations of this out there. But basically a type specifies the 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/trait also has an associated type. However, the reciprocal is typically not true: not all types have a corresponding class/interface/trait. For example, your C with T is a type, but not a class nor a trait (nor even a combination thereof).

The extends clauses expects classes and traits (separated by with), but not one type. This is because extends means: extend the behavior of this thing. As I said, types do not define behavior.

In most places, the syntax A with B represents a type which is a subtype of both the type A and the type B. In the extends clause, however, with takes a different meaning, and simply acts as a separator for the arguments of extends (much like , acts as separator for arguments to a method call).

If you write class X extends C with T, it will work, because it means class X extends C, T, if you want.

HTH



回答2:

String is a final class, cannot be extended.