andThen用于Scala中两个参数的函数 [英] andThen for function of two arguments in Scala
问题描述
假设我有两个函数 f
和 g
:
val f: (Int, Int) => Int = _ + _
val g: Int => String = _ + ""
现在我想用 andThen
组合它们以获得函数 h
Now I would like to compose them with andThen
to get a function h
val h: (Int, Int) => String = f andThen g
很遗憾,它无法编译:(
Unfortunately it doesn't compile :(
scala> val h = (f andThen g)
<console> error: value andThen is not a member of (Int, Int) => Int
val h = (f andThen g)
为什么不编译以及如何编写 f
和 g
以获得(Int,Int)=>字符串
?
Why doesn't it compile and how can I compose f
and g
to get (Int, Int) => String
?
推荐答案
它不会编译,因为 andThen
是 Function1
的方法(一个参数的函数:请参见 scaladoc ).
It doesn't compile because andThen
is a method of Function1
(a function of one parameter: see the scaladoc).
您的函数 f
具有两个参数,因此将是 Function2
的一个实例(请参见
Your function f
has two parameters, so would be an instance of Function2
(see the scaladoc).
要使其编译,您需要通过以下方式将 f
转换为一个参数的函数:
To get it to compile, you need to transform f
into a function of one parameter, by tupling:
scala> val h = f.tupled andThen g
h: (Int, Int) => String = <function1>
测试:
scala> val t = (1,1)
scala> h(t)
res1: String = 2
You can also write the call to h
more simply because of auto-tupling, without explicitly creating a tuple (although auto-tupling is a little controversial due to its potential for confusion and loss of type-safety):
scala> h(1,1)
res1: String = 2
这篇关于andThen用于Scala中两个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!