首页 > 解决方案 > 函数组合导致方法首先缺少参数列表

问题描述

假设我们有以下函数:

def first(a: A): B = ???
def second(b: B): C = ???

我想用 来组合它们andThen,但是下面的代码:

(first andThen second)(a)

结果是:

<console>:14: error: missing argument list for method first
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `first _` or `first(_)` instead of `first`.                                                                                                                                                                    
(first andThen second) (1)

标签: scalafunctional-programmingcomposition

解决方案


andThen()是 a 上的一个方法Function。正如您所定义的,它first()是一个方法 ( def),而不是一个函数。那些是不同的实体

您可以将其定义为函数...

val first : A => B = (a:A) => ???

...或者您可以使用eta 扩展将其提升为功能状态。

(first _ andThen second)

据说 Scala 3 将提供更透明的 eta 扩展机制,这样方法和函数之间的区别就不会那么麻烦了。


推荐阅读