扩展类型和类型有什么区别

时间:2015-11-26 13:45:11

标签: scala

定义Hello和World trait

trait Hello

trait World

这没问题

trait Right extends Hello with World

但是这有编译错误

type HelloWorld = Hello with World

trait Error extends HelloWorld
//Error:(9, 22) class type required but A$A65.this.Hello with A$A65.this.World found

2 个答案:

答案 0 :(得分:3)

extends后只能有一个类或一个特征,而Hello with World都不是(它是一个复合类型)。 extends Hello with World应理解为“使用Hello扩展World”,而不是“扩展Hello with World”。

答案 1 :(得分:2)

根据SLS 5.3,trait Hellotrait Hello extends AnyRef的缩写(“extends子句[...]可以省略,在这种情况下假定extends scala.AnyRef

根据SLS 5.1,“可以编写以特征引用开头的父母列表[...]在这种情况下,父母列表被隐式扩展为包括mt1的超类型作为第一父类型。“

因此trait Right extends Hello with World实际上是trait Right extends AnyRef with Hello with World的缩写。

至于为什么使用类型别名搞砸了,如果你看一下语法定义,语法不是extends <type>,而是字面意思extends <sc> with <mt1> with <mt2> ...。复合类型的语法在SLS 3.2.7中单独定义。它看起来像是相同的语法,但它并不完全相同。

相关问题