在 2.8.1/2.9.0.1 REPL 中尝试以下操作,第一个给出错误。

val l = List(Vector(1,2), List(3,4,5))
error: type mismatch;
 found   : scala.collection.immutable.Vector[Int]
 required: scala.collection.immutable.Seq[Int]{def companion:     scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]; protected def thisCollection: Seq[Int]{def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}; def dropRight(n: Int): scala.collection.immutable.Seq[Int]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]}; def takeRight(n: Int): scala.collection.immutable.Seq[Int]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]}; def slice(start: Int,end: Int): scala.collection.immutable.Seq[Int]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable....
      val l = List(Vector(1,2), List(3,4,5))
                         ^
:5: error: type mismatch;
 found   : List[Int]
 required: scala.collection.immutable.Seq[Int]{def companion:     scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]; protected def thisCollection: Seq[Int]{def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}; def dropRight(n: Int): scala.collection.immutable.Seq[Int]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]}; def takeRight(n: Int): scala.collection.immutable.Seq[Int]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]}; def slice(start: Int,end: Int): scala.collection.immutable.Seq[Int]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]}; def take(n: Int):...
       val l = List(Vector(1,2), List(3,4,5))
                                    ^

虽然这成功了:
val l = List[Seq[Int]](Vector(1,2), List(3,4,5))
//evaluates fine to List[Seq[Int]] = List(Vector(1, 2), List(3, 4, 5))

在第一种情况下,scala 试图推断的类型是什么?它是具有结构类型的 Seq 吗?为什么不能统一Vector和List?这是一些缺失的功能,还是通过这种方式(需要明确的类型定义)以防止我的脚开枪?

最佳答案

这显然是类型推断器中的一个错误,现在已在 中修复了 scala 2.9.1 :

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Server VM, Java 1.6.0_18).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import collection.immutable._
import collection.immutable._

scala>  List(Vector(1, 2, 3), List(4, 5))
res0: List[scala.collection.immutable.Seq[Int]] = List(Vector(1, 2, 3), List(4, 5))

关于Scala - 为什么不能为包含 Vector 和 List 的列表推断 Seq 列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7411809/

10-10 18:06