我想将2个Scala函数合并到andThen
的第3个函数中,但遇到了类型系统的问题。
以下是代码:
object Test{
def process1[T](in : List[T]) : List[T] = in
def process2[T](in : List[T]) : List[T] = in
//this works fine but you have to read it inside out
def combined2[T](in : List[T]) : List[T] = process2(process1(in))
//this also works but at the cost of creating a new function every time
def combined3[T](in : List[T]) : List[T] = {
(process1[T] _ andThen process2[T] _)(in)
}
//this doesn't work. it is a function List[Nothing] => List[Nothing]
val combined = process1 _ andThen process2 _
def main(s : Array[String]) {
val input : List[Int] = List(1,2,3)
val out1 : List[Int] = process1(input)
val combinedOut2 : List[Int] = combined2(input)
val combinedOut3 : List[Int] = combined3(input)
//this will not compile as combined is [List[Nothing] => List[Nothing]
//val combinedOut : List[Int] = combined(input)
}
}
是否有一种很好的方法可以将combined
的值设置为List[T]
到List[T]
的函数,或者这是类型擦除的基本问题?
答案 0 :(得分:1)
不确定它是否不错,但combined3
可以缩短为:
def combined3[T] = process1[T] _ andThen process2[T] _
每次都可以针对每种情况优化函数实例的创建:
val combinedInt = combined3[Int]
combinedInt(input)
答案 1 :(得分:0)
你可以用这种方式组合功能,它更干净
implicit class FunctionCombiner[T, U](fn: T => U) {
def &&&(f: T => U): T => U = {
(t: T) => {
fn(t); f(t)
}
}
}
在此之后,您可以运行如下语句:
val f1 = (i: Int) => println((1*i).toString)
val f2 = (i: Int) => println((2*i).toString)
val f3 = (i: Int) => println((3*i).toString)
val f = f1 &&& f2 &&& f3
f(5)
这会产生结果:
5
10
15