Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 创建类型别名的实例会导致;“所需类别类型”;错误_Scala - Fatal编程技术网

Scala 创建类型别名的实例会导致;“所需类别类型”;错误

Scala 创建类型别名的实例会导致;“所需类别类型”;错误,scala,Scala,通过将observeSet与HashSet混合在一起创建了一个新类型,我有点期待替换,然后能够使用新类型创建一个新实例,如下面的“foo”所示。但这不会编译,尽管使用原始的长格式类型似乎很好(如下面的“bar”所示) 这只是语言的一个特点,还是我做了一些愚蠢的事 package whatever import collection.mutable._ object Whatever { type ObservableHashSet[T] = HashSet[T] with Obser

通过将
observeSet
HashSet
混合在一起创建了一个新类型,我有点期待替换,然后能够使用新类型创建一个新实例,如下面的“foo”所示。但这不会编译,尽管使用原始的长格式类型似乎很好(如下面的“bar”所示)

这只是语言的一个特点,还是我做了一些愚蠢的事

package whatever

import collection.mutable._
object Whatever {

  type ObservableHashSet[T] = HashSet[T]  with  ObservableSet[T]
  class X


  def foo {
       new  ObservableHashSet[X]
  }

   def bar {
    new HashSet[X]  with  ObservableSet[X]
  }
}
错误是

error: class type required but scala.collection.mutable.HashSet[scala.Whatever.X] with scala.collection.mutable.ObservableSet[scala.Whatever.X] found
new  ObservableHashSet[X]

简单的版本是,您已经为结构类型(不能实例化)创建了类型别名

这是您所做工作的简化版本(不起作用):

所以,问题是:为什么scala允许您创建无法实例化的类型别名? 好的,
类型observeHashSet[T]=HashSet[T]和observeSet[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!
但如果我们尝试使用不符合结构类型的参数调用test,则会出现类型不匹配:

scala> test(new HashSet[String])
<console>:13: error: type mismatch;
 found   : scala.collection.mutable.HashSet[String]
 required: ObservableHashSet[String]
scala>test(新的HashSet[String])
:13:错误:类型不匹配;
找到:scala.collection.mutable.HashSet[String]
必需:ObservableHashSet[字符串]

谢谢你,保罗。我想我认为“类型”是一种宏观替代。。我将阅读更多关于结构类型的内容。thx@Richard:谢谢你的提问。在你提问之前我也不知道答案,用“类型”做实验很有启发性。
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]