为什么map和Set在scala.Predef中有别名?

Jim*_*Jim 7 scala

10次​​中的9次,只是使用MapSet表现得像我期望的那样,但偶尔会出乎意料地被击中

error: type mismatch; 
[INFO]  found   : scala.collection.Set[String]
[INFO]  required: Set[String]
Run Code Online (Sandbox Code Playgroud)

例如,来自REPL:

scala> case class Calculator[+T](name: String, parameters: Set[String])
defined class Calculator

scala> val binding=Map.empty[String, String]
binding: scala.collection.immutable.Map[String,String] = Map()

scala> Calculator("Hello",binding.keySet)
<console>:9: error: type mismatch;
found   : scala.collection.Set[String]
required: Set[String]
       Calculator("Hello",binding.keySet)
                                  ^
Run Code Online (Sandbox Code Playgroud)

我想我理解错误,即对别名类型的函数调用返回实际类型.

因此在我看来解决方案是导入无别名的类型.在我的项目中的每个其他文件现在将生成类型不匹配错误,所以我将不得不在每个文件中导入它.这导致了我在标题中提出的问题 - Predef中别名的目的是什么,如果最终我还需要导入实际的包?

我的理解是否有缺陷,或者我的用例不是典型的,或两者兼而有之?

psp*_*psp 12

你误解了这个问题.并不是它不能识别类型别名与别名的类型相同.这是类型别名是scala.collection.immutable.Set,它与scala.collection.Set不同.

编辑:顺便说一句,我认为我已经解决了这个问题,正如类型诊断中的注释所证明的那样:

   ... Also, if the
*  type error is because of a conflict between two identically named
*  classes and one is in package scala, fully qualify the name so one
*  need not deduce why "java.util.Iterator" and "Iterator" don't match.
Run Code Online (Sandbox Code Playgroud)

显然需要更多的工作.

编辑2010年7月17日:好的,我花了很长时间,但现在至少它说了一些难以误解的东西.

files/neg/type-diagnostics.scala:4: error: type mismatch;
 found   : scala.collection.Set[String]
 required: scala.collection.immutable.Set[String]
  def f = Calculator("Hello",binding.keySet)
                                     ^
Run Code Online (Sandbox Code Playgroud)

  • 我不知道.因为这是某人写它的方式.除非另有说明,否则我倾向于认为事情没有特别的原因. (2认同)