简要版本是,你已经创建了一个类型别名结构类型(你不能实例化)。
这是你做了什么的简化版本(不工作):
scala> import collection.mutable._
import collection.mutable._
scala> type ObservableHashSet[T] = HashSet[T] with ObservableSet[T]
defined type alias ObservableHashSet
scala> new ObservableHashSet[String]
<console>:12: error: class type required but scala.collection.mutable.HashSet[String] with scala.collection.mutable.ObservableSet[String] found new ObservableHashSet[String]
现在,错误确实让一些感觉,让我尝试解释为什么。
使用type ObservableHashSet[T] = HashSet[T] with ObservableSet[T]
您正在为非具体类型的东西定义类型别名(或者,如错误消息所述,不是“类类型”),因此您无法使用new
创建它的实例。
但是,这(与我们开展创建一个类类型的中间步骤)的工作原理:
scala> class ObservableHashSet[T] extends HashSet[T] with ObservableSet[T]
defined class ObservableHashSet
scala> type obs[T] = ObservableHashSet[T]
defined type alias obs
scala> new obs[String]
res1: ObservableHashSet[String] = Set()
所以,问题是:为什么斯卡拉让你创建一个类型别名,你不能实例化? 那么,type ObservableHashSet[T] = HashSet[T] with ObservableSet[T]
是一个结构类型。虽然,正如您在第一段代码中看到的那样,您无法创建它的实例,但仍然可以使用它:例如对一个函数的参数进行结构约束。
请看:
scala> type ObservableHashSet[T] = HashSet[T] with ObservableSet[T]
defined type alias ObservableHashSet
scala> def test(obsHashSet: ObservableHashSet[String]) : String = {"bingo!"}
test: (obsHashSet: ObservableHashSet[String])String
scala> test(new HashSet[String] with ObservableSet[String])
res4: String = bingo!
但如果我们试图调用测试与不符合结构类型,我们得到一个类型不匹配的参数:
scala> test(new HashSet[String])
<console>:13: error: type mismatch;
found : scala.collection.mutable.HashSet[String]
required: ObservableHashSet[String]
感谢保罗。我想我正在考虑“类型”作为一种宏观替代。我会更多地阅读一些结构类型。 thx – Richard
@Richard:谢谢你的提问。在你问及试验“类型”是否有启发性之前,我不知道答案。 –