我怎么才能把这事做好?我手头的任务有点复杂,但归根结底是这样的:
object Z {
class B extends Function1[Int, Int] {
def apply(i: Int): Int = i
}
def compose[T <: Function1[X, X], X](fcts: List[T]): Function1[X, X] = {
fcts.reduce(_ andThen _)
}
def test() = {
val fcts = List.empty[B]
// Unspecified type parameter X
val composed: Function1[Int, Int] = compose[B](fcts)
}
}我不知道如何定义“组合”函数,以便能够接收到一些具体的B类并自动推断出依赖类型X
发布于 2017-04-05 20:49:59
Scala编译器在试图像您这样推断多个级别的类型参数时做得不好。相反,删除T <: Function1[X, X]更简单,只需要一个表示Function1的参数和返回类型的类型参数。
def compose[A](fcts: List[Function1[A, A]]): Function1[A, A] = {
fcts.reduce(_ andThen _)
}编译器只需推断A就可以轻松得多,而不是试图找出T和X是什么,当X是T类型的一部分时。
val a: Int => Int = _ + 10
val b: Int => Int = _ * 2
val c: Int => Int = _ - 3
scala> val f = compose(List(a, b, c))
f: Int => Int = scala.Function1$$Lambda$1187/930987088@531ec2ca
scala> f(2)
res1: Int = 21注意,reduce将为一个空的函数列表抛出一个异常。
https://stackoverflow.com/questions/43241204
复制相似问题