在下面的代码中,为什么编译器在传递给函数 imSeq 时无法推断 x1 是不可变的。
def imSeq(e: scala.collection.immutable.Seq[Int]) = e.foreach(println)
def mSeq(e: Seq[Int]) = e.foreach(println)
scala> val x1 = Seq(1, 2, 3)
x1: Seq[Int] = List(1, 2, 3)
scala> x1.isInstanceOf[scala.collection.immutable.List[Int]]
res11: Boolean = true
scala> x1.isInstanceOf[scala.collection.immutable.Seq[Int]]
res12: Boolean = true
scala> x1.isInstanceOf[scala.collection.mutable.Seq[Int]]
res13: Boolean = false
scala> imSeq(x1)
<console>:10: error: type mismatch;
found : Seq[Int]
required: scala.collection.immutable.Seq[Int]
imSeq(x1)
^
答案 0 :(得分:3)
这是因为您在函数中明确要求immutable.Seq
的实例,但pre-imported Seq
trait不仅仅是immutable.Seq
的别名,它实际上是immutable.Seq
的基本特征。换句话说,immutable.Seq
extends Seq
。
概括接受的类型:
def imSeq(e: Seq[Int]) = e.foreach(println)