有没有办法提取或询问部分应用的函数以获得应用的值。例如,可以从下面代码中的reduceBy3中提取值3。
def subtract(x:Int, y:Int) = x-y
val reduceBy3 = subtract(3,_:Int)
我已经尝试创建一个提取器,如下例所示,但是 unapply 方法必须接受一个需要询问的 (Int=>Int) 函数。
class ReduceBy(y: Int) {
val amt = y
def subtract(y: Int, x: Int) = x - y
}
object ReduceBy extends Function1[Int, Int => Int] {
def apply(y: Int) = {
val r = new ReduceBy(y)
r.subtract(y, _: Int)
}
def unapply(reduceBy: ReduceBy): Option[Int] = Some(reduceBy.amt)
}
object ExtractPartialApplied extends App {
val r3 = ReduceBy(3)
val extract = r3 match {
case ReduceBy(x) => ("reduceBy", x)
case x: ReduceBy => ("reduceBy", x.amt)
case _ => ("No Match", 0)
}
println(extract)
val z = r3(5)
println(z)
}