考虑以下代码:(请参阅下面的实际代码,需要解决)
def applyAll[T,S, U <: Seq[T => S]](l : U, x: T) = l.map(f => f(x))
val u = List((i: Int) => i + 1, (i: Int) => i + 2)
println(applyAll(u,1))
(给定Seq
T => S
和一个值,我们希望获得应用于此值的功能)。
虽然applyAll
编译正常,但在u
上调用它会出现以下错误:
Error:(35, 13) inferred type arguments [Int,Nothing,List[Int => Int]] do not conform to method applyAll's type parameter bounds [T,S,U <: Seq[T => S]]
println(applyAll(u,1))
^
这表明编译器无法推断类型参数S
,我猜测它是因为它在函数类型T => S
内“嵌套”。
修改:
我试图修复的实际代码类似(尽管很复杂),并且无法通过删除U参数来修复。这是:
def applyNatural[T, S, Repr <: TraversableLike[T => S, Repr], That]
(data: T, jobs: Repr)
(implicit bf: CanBuildFrom[Repr, S, That]): That = {
jobs.map(f => f(data))
}
val u = List((i: Int) => i + 1, (i: Int) => i + 2)
val v = applyNatural(1, u)
println(v)
答案 0 :(得分:4)
U
根本没用。只需写下
def applyAll[T,S](l : Seq[T => S], x: T) = l.map(f => f(x))
val u = List((i: Int) => i + 1, (i: Int) => i + 2)
println(applyAll(u,1))
答案 1 :(得分:3)
您可以将Repr
设为更高级别的Repr[_]
类型,并使jobs
参数的类型为Repr[T => S]
:
def applyNatural[T, S, Repr[A] <: TraversableLike[A, Repr[A]], That]
(data: T, jobs: Repr[T => S])
(implicit bf: CanBuildFrom[Repr[T => S], S, That]
): That = {
jobs.map(f => f(data))
}