【问题标题】:Function composition results in missing argument list for method first函数组合导致方法首先缺少参数列表
【发布时间】:2020-06-28 12:34:15
【问题描述】:

假设我们有以下函数:

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)

【问题讨论】:

    标签: scala functional-programming composition


    【解决方案1】:

    andThen()Function 上的一个方法。正如您所定义的,first() 是一个方法 (def),而不是一个函数。那些是different entities

    你可以把它定义为一个函数...

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

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

    (first _ andThen second)
    

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

    【讨论】:

    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多