组合和然后方法 [英] Compose and andThen methods
问题描述
我正在学习教程 模式匹配 &Scala compose
和 andThen
方法上的函数组合.有这样一个例子:
I'm following the tutorial Pattern matching & functional composition on Scala compose
and andThen
methods. There's such an example:
scala> def addUmm(x: String) = x + " umm"
scala> def addAhem(x: String) = x + " ahem"
val ummThenAhem = addAhem(_).compose(addUmm(_))
当我尝试使用它时出现错误:
When I try to use it I get an error:
<console>:7: error: missing parameter type for expanded function ((x$1) => addAhem(x$1).compose(((x$2) => addUmm(x$2))))
val ummThenAhem = addAhem(_).compose(addUmm(_))
^
<console>:7: error: missing parameter type for expanded function ((x$2) => addUmm(x$2))
val ummThenAhem = addAhem(_).compose(addUmm(_))
^
<console>:7: error: type mismatch;
found : java.lang.String
required: Int
val ummThenAhem = addAhem(_).compose(addUmm(_))
但是,这是有效的:
val ummThenAhem = addAhem _ compose addUmm _
甚至
val ummThenAhem = addAhem _ compose addUmm
教程中的代码有什么问题?后一个表达式不是和第一个没有括号的表达式一样吗?
What's wrong with the code in the tutorial? Isn't the latter expression the same as the first one without parenthesis?
推荐答案
addAhem
是一种方法.compose
方法定义在函数上.addAhem _
将 addAhem
从方法转换为函数,因此可以在其上调用 compose
.compose
需要一个函数作为参数.您通过将 addUmm
转换为带有 addUmm _
的函数(下划线可以省略,因为编译器可以自动转换当它知道无论如何都需要一个函数时将方法转换为函数).所以你的代码:
addAhem
is a method. compose
method is defined on functions. addAhem _
converts addAhem
from method to function, so compose
can be called on it. compose
expects a function as it's argument. You are giving it a method addUmm
by converting addUmm
into a function with addUmm _
(The underscore can be left out because the compiler can automatically convert a method into a function when it knows that a function is expected anyway). So your code:
addAhem _ compose addUmm
与
(addAhem _).compose(addUmm)
但不是
addAhem(_).compose(addUmm(_))
附注我没有看你提供的链接.
PS I didn't look at the link you provided.
这篇关于组合和然后方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!