在方法中包装时的不同行为:scala
我的代码有两种,而且都有效: 直接使用在方法中包装时的不同行为:scala,scala,scala-collections,Scala,Scala Collections,我的代码有两种,而且都有效: 直接使用展平 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 } 出现
展平
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
不同。泛型表示“在列表中一致的某种类型”
,而Any
表示“我对列表中的任何元素一无所知”
因此,不能展平列表[Any]
,因为编译器对列表的内容一无所知。列表[List[Any]
可以展平,但结果是一个列表[Any]
,它没有列表[A]
有用,因为编译器将赋予A
(Int
,Char
,String
,…)一个含义,这就是您将得到的(List[Int]/code>,List[Char]
,列表[字符串]
,…)