andThen用于Scala中两个参数的函数 [英] andThen for function of two arguments in Scala

查看:67
本文介绍了andThen用于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆