实际上,您可以部分应用任何您想要的方法。只需调用该方法并省略参数即可:
scala> def foo(a: Int, b: Int) = a*b
foo: (a: Int, b: Int)Int
scala> val x = foo(1,_: Int)
x: Int => Int = <function1>
scala> def bar(x: Int, y: Int, z: Int) = x*y+z
bar: (x: Int, y: Int, z: Int)Int
scala> bar(2,_:Int,6)
res0: Int => Int = <function1>
唯一的区别是,您必须告诉编译器缺少参数的类型,否则它无法在重载方法之间做出决定。
另一种方式,如果你有一个真正的函数而不是方法,那就是调用curried
关于函数:
scala> val f = {(x:Int, y:Int) => x*y}
f: (Int, Int) => Int = <function2>
scala> f.curried
res2: Int => (Int => Int) = <function1>
您还可以使用以下方法从方法创建函数_
:
scala> bar _
res6: (Int, Int, Int) => Int = <function3>
然后打电话curried
对此:
scala> (bar _).curried
res5: Int => (Int => (Int => Int)) = <function1>