andThen 对于 Scala 中两个参数的函数

2024-01-11

假设我有两个函数f and g:

val f: (Int, Int) => Int = _ + _
val g: Int => String = _ +  ""

现在我想用andThen得到一个函数h

val h: (Int, Int) => String = f andThen g

不幸的是它无法编译:(

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

为什么它不能编译以及我该如何编写f and g to get (Int, Int) => String ?


它无法编译,因为andThen是一种方法Function1(只有一个参数的函数:参见scaladoc http://www.scala-lang.org/api/current/index.html#scala.Function1).

你的职能f有两个参数,所以将是一个实例Function2(参见scaladoc http://www.scala-lang.org/api/current/index.html#scala.Function2).

为了让它编译,你需要转换f通过元组转换为一个参数的函数:

scala> val h = f.tupled andThen g
h: (Int, Int) => String = <function1>

test:

scala> val t = (1,1)
scala> h(t)
res1: String = 2

您还可以将调用写入h更简单的是因为自动组合 https://stackoverflow.com/questions/5997553/why-and-how-is-scala-treating-a-tuple-specially-when-calling-a-one-arg-function,无需显式创建元组(尽管自动元组由于其潜在的混乱和类型安全性的损失而存在一些争议):

scala> h(1,1)
res1: String = 2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

andThen 对于 Scala 中两个参数的函数 的相关文章

随机推荐