Why `trait T; class C; class X extends (C with T)` can't be compiled?

混江龙づ霸主 提交于 2020-01-01 17:01:10

问题


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.



来源:https://stackoverflow.com/questions/25960083/why-trait-t-class-c-class-x-extends-c-with-t-cant-be-compiled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!