我正在按照斯卡拉compose
和andThen
方法的教程Pattern matching & functional composition。有这样一个例子:撰写和然后方法
scala> def addUmm(x: String) = x + " umm"
scala> def addAhem(x: String) = x + " ahem"
val ummThenAhem = addAhem(_).compose(addUmm(_))
当我尝试使用它,我得到一个错误:
<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
教程中的代码有什么问题?不是后者的表达与没有括号的第一个表达式相同吗?
为了完整起见,andThen例子是这样的:。 'VAL ahemThenUmm = addAhem(_)andThen(addUmm(_))' 时,它应该像 'VAL ahemThenUmm1 =(addAhem _)andThen(addUmm )' –
我不太确定用圆括号写的部分;编译器*不会*将方法自动转换为函数,至少对于Scala 2.10.2来说。解决方法是声明'addAhem'和'addUmm'作为函数,这样'compose'或'和Then'就不用'_'工作。 –