Scala assumes wrong type when using foldLeft

2019-08-30 00:41发布

问题:

I am trying to create a cross product function in Scala, where k is the number of times I build the cross product.

val l = List(List(1), List(2), List(3))
(1 to k).foldLeft[List[List[Int]]](l) { (acc: List[List[Int]], _) =>
    for (x <- acc; y <- l)
        yield x ::: l
}

However, this code does not compile:

test.scala:9: error: type mismatch;
    found   : List[List[Any]]
    required: List[List[Int]]
    for (x <- acc; y <- l)
           ^

Why does it ever think I have a List[Any]'s there? Clearly everything I am dealing with is Lists of Ints.

回答1:

Your for comprehension is effectively yielding List[List[Int or List[Int]]] hence the inferred type is List[List[Any]]. Here's an example from the repl:

scala> val l = List(List(1), List(2), List(3))
l: List[List[Int]] = List(List(1), List(2), List(3))
val x = for {
     |     x <- l
     |     y <- l
     |   } yield x ::: l
x: List[List[Any]] = List(List(1, List(1), List(2), List(3)), List(1, List(1), List(2), List(3)), List(1, List(1), List(2), List(3)), List(2, List(1), List(2), List(3)), List(2, List(1), List(2), List(3)), List(2, List(1), List(2), List(3)), List(3, List(1), List(2), List(3)), List(3, List(1), List(2), List(3)), List(3, List(1), List(2), List(3)))