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

标签 scala functional-programming composition

假设我们有以下函数:

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)

最佳答案

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

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

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

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

(first _ andThen second)

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

关于scala - 函数组合导致方法首先缺少参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618108/

相关文章:

python - 使用对象组合时每次都实例化一个唯一的对象?

python - 实现表示 "a list with a title"的类的 pythonic 方法是什么?

Scala - 如何使用计时器而不阻塞 Futures 与 Await.result

javascript - 如何从头开始用 Javascript 编写异步 Map 函数?

functional-programming - 不可变的游戏对象,基本的函数式编程问题

javascript - 在没有 lodash 的情况下 curry 我的函数

Scala Spark - 将元组的值映射到单个值

scala - 为什么 Buffer 不是 IndexedSeq 的子类?

json - 玩 - 尝试实现写入列表[任何]

xml - 组合子元素的 XSLT 多文档输出