包装在方法中时的不同行为:scala

Different behaviour when wrapping in a method : scala

我的代码有两种,并且有效:

一个直接用flatten

val list = List(List(1, 2), List(3, 4))
println(list.flatten)

其他使用方法

val list = List(List(1, 2), List(3, 4))
println(flatten(list))

def flatten(list: List[Any]): List[Any] = {
        list.flatten//this is the line 28
}

出现错误:

Error:(28, 14) No implicit view available from Any => scala.collection.GenTraversableOnce[B].
        list.flatten

Error:(28, 14) not enough arguments for method flatten: (implicit asTraversable: Any => scala.collection.GenTraversableOnce[B])List[B].
Unspecified value parameter asTraversable.
        list.flatten

为什么以及如何解决?

这就是你想要的方法。

def flatten[A](list: List[List[A]]): List[A] = {
  list.flatten
}

泛型 A(或者你想给它起的任何名字)不同于类型 Any。泛型表示 "some type that is consistent within the List" 而 Any 表示 "I don't know anything about any of the elements within the List".

所以 List[Any] 不能被展平,因为编译器对列表的内容一无所知。 List[List[Any]] 可以展平,但结果是 List[Any],它不如 List[A] 有用,因为编译器会给 A 赋予意义(Int, Char, String, ....) 这就是您将得到的结果 (List[Int], List[Char], List[String], .... ).