函数组合导致首先缺少方法的参数列表

And*_*cus 2 functional-programming scala composition

假设我们有以下功能:

def first(a: A): B = ???
def second(b: B): C = ???
Run Code Online (Sandbox Code Playgroud)

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

(first andThen second)(a)
Run Code Online (Sandbox Code Playgroud)

结果是:

<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)
Run Code Online (Sandbox Code Playgroud)

jwv*_*wvh 5

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

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

val first : A => B = (a:A) => ???
Run Code Online (Sandbox Code Playgroud)

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

(first _ andThen second)
Run Code Online (Sandbox Code Playgroud)

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