use*_*ser 0 syntax functional-programming scala
有可能有像这样的语法(parameter1, parameter2) applied myFunction.这里myFunction将应用于给定的参数.具体示例:val myFunction = (a:String) => a+a+"there"; "hello" applied myFunction应输出"hellohellothere".我知道这是可能的(parameter1, parameter2) match {case myFunctionWrittenOut},所以上面会变成"hello" match {case a:String => a+a+"there"}但在这里你必须写出函数:你不能使用引用.
我不认为标准scala是可能的.但是你可以编写一些辅助方法来实现这样的东西:
implicit class Applied1[T](val t: T) extends AnyVal {
def applied[R](f: T => R): R = f(t)
}
implicit class Applied2[T1, T2](val t: (T1, T2)) extends AnyVal {
def applied[R](f: (T1, T2) => R): R = f(t._1, t._2)
}
implicit class Applied3[T1, T2, T3](val t: (T1, T2, T3)) extends AnyVal {
def applied[R](f: (T1, T2, T3) => R): R = f(t._1, t._2, t._3)
}
// ... and 19 more implicit classes: Applied4 to Applied22
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
def minus(a: Int): Int = -a
def plus(a: Int, b: Int): Int = a + b
def plus(a: Int, b: Int, c: Int): Int = a + b + c
scala> 5 applied minus
res0: Int = -5
scala> (1, 2) applied plus
res1: Int = 3
scala> (1, 2, 3) applied plus
res2: Int = 6
Run Code Online (Sandbox Code Playgroud)
但是使用泛型函数或带隐式参数的函数可能会有点复杂:
def mul[T : Numeric](a: T, b: T): T = {
import Numeric.Implicits._
a * b
}
scala> (1.5, 2.5) applied (mul(_, _))
res3: Double = 3.75
Run Code Online (Sandbox Code Playgroud)