如果我传递底层类型,为什么期望类型别名输入的函数没有进行类型检查?

时间:2014-07-15 15:47:09

标签: scala scala-collections

在下面的代码中,为什么编译器在传递给函数 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)
                ^

1 个答案:

答案 0 :(得分:3)

这是因为您在函数中明确要求immutable.Seq的实例,但pre-imported Seq trait不仅仅是immutable.Seq的别名,它实际上是immutable.Seq的基本特征。换句话说,immutable.Seq extends Seq

概括接受的类型:

def imSeq(e: Seq[Int]) = e.foreach(println)