然后是Scala中两个参数的功能

Mic*_*ael 6 scala function

假设我有两个函数fg:

val f: (Int, Int) => Int = _ + _
val g: Int => String = _ +  ""
Run Code Online (Sandbox Code Playgroud)

现在我想用它们来组合它andThen来获得一个功能h

val h: (Int, Int) => String = f andThen g
Run Code Online (Sandbox Code Playgroud)

不幸的是它没有编译:(

scala> val h = (f andThen g)
<console> error: value andThen is not a member of (Int, Int) => Int
   val h = (f andThen g)
Run Code Online (Sandbox Code Playgroud)

为什么不把它编译,我该如何撰写fg获得(Int, Int) => String

DNA*_*DNA 10

它不编译,因为它andThen是一个方法Function1(一个参数的函数:参见scaladoc).

你的函数f有两个参数,所以是一个实例Function2(参见scaladoc).

要使其编译,您需要f通过tupling 转换为一个参数的函数:

scala> val h = f.tupled andThen g
h: (Int, Int) => String = <function1>
Run Code Online (Sandbox Code Playgroud)

测试:

scala> val t = (1,1)
scala> h(t)
res1: String = 2
Run Code Online (Sandbox Code Playgroud)

您也可以h更简单地编写调用因为自动编组,而无需显式创建元组(尽管由于混淆和类型安全性丢失,自动编组有点争议):

scala> h(1,1)
res1: String = 2
Run Code Online (Sandbox Code Playgroud)


Mic*_*jac 6

Function2没有andThen方法.

但是,您可以手动编写它们:

val h: (Int, Int) => String = { (x, y) => g(f(x,y)) }
Run Code Online (Sandbox Code Playgroud)