scala:list.flatten:没有隐式参数匹配参数类型(Any)=> Iterable [Any]被发现 [英] scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found
问题描述
在scala 2.7.6中编译此代码:
def flatten1(l:List [Any]):List [Any ] = l.flatten
我得到错误:
无隐式参数匹配参数类型(Any)=>已找到Iterable [Any]
为什么?
如果你希望能够扁平列表(1,2,列表(3,4),5)
into List(1,2,3,4,5)
,那么你需要类似的:
implicit def any2iterable [A](a:A):Iterable [A] = Some(a)
随着:
val list:List [Iterable [Int]] = List 2,List(3,4),5)//提供列表类型
//导致隐式
//转换被调用
println(list.flatten => itr))// List(1,2,3,4,5)
strong> EDIT : flat a
List [Int]
时,您是否希望发生你期望的功能总和列表
中的 Int
如果是,您应该在 2.8.x 中查看新的合并函数:
val list = List(1,2,3)
println(list.sum)// 6
compiling this code in scala 2.7.6:
def flatten1(l: List[Any]): List[Any] = l.flatten
i get the error:
no implicit argument matching parameter type (Any) = > Iterable[Any] was found
why?
If you are expecting to be able to "flatten" List(1, 2, List(3,4), 5)
into List(1, 2, 3, 4, 5)
, then you need something like:
implicit def any2iterable[A](a: A) : Iterable[A] = Some(a)
Along with:
val list: List[Iterable[Int]] = List(1, 2, List(3,4), 5) // providing type of list
// causes implicit
// conversion to be invoked
println(list.flatten( itr => itr )) // List(1, 2, 3, 4, 5)
EDIT: the following was in my original answer until the OP clarified his question in a comment on Mitch's answer
What are you expecting to happen when you flatten
a List[Int]
? Are you expecting the function to sum the Int
s in the List
? If so, you should be looking at the new aggegation functions in 2.8.x:
val list = List(1, 2, 3)
println( list.sum ) //6
这篇关于scala:list.flatten:没有隐式参数匹配参数类型(Any)=> Iterable [Any]被发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!