问题描述
Scala 代码:
trait T
class C
type W = C with T
class X extends W
W
是一个类型别名,但我想定义一个类来扩展它.为什么以及如何修复它?
W
is a type alias, but I want define a class to extend it. Why and how to fix it?
推荐答案
我很难以一种很好的方式构建我的答案,但这里仍然试图解释正在发生的事情:
I have difficulty structuring my answer in a nice way, but here is nevertheless an attempt at explaining what's going on:
您会收到编译错误,因为 extends
子句需要类和特征,而不是类型,并且您提供的是类型.类和特征不能与类型混淆.
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.
在大多数静态类型的面向对象语言中,每个类/接口/特征也有一个关联的类型.然而,倒数通常不是真的:并非所有类型都有相应的类/接口/特征.例如,你的 C with T
是一个类型,但不是一个类,也不是一个特征(甚至不是它们的组合).
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).
extends
子句需要类和特征(由 with
分隔),但不是一种类型.这是因为extends
的意思是:扩展这个东西的行为.正如我所说,类型不定义行为.
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.
在大多数地方,语法 A with B
代表一个 type,它是 A
类型和 类型的子类型>B
.然而,在 extends
子句中,with
具有不同的含义,它只是作为 extends
参数的分隔符(很像 >,
作为方法调用参数的分隔符).
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).
如果你写class X extends C with T
,它会起作用,因为它意味着class X extends C, T
,如果你愿意的话.
If you write class X extends C with T
, it will work, because it means class X extends C, T
, if you want.
HTH
这篇关于为什么`特质T;C级;class X extends (C with T)` 无法编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!