Scala函数定义参数列表中的不同括号样式

use*_*321 6 functional-programming scala function higher-order-functions

Scala中以下两个函数定义的区别是什么:

1) def sum(f: Int => Int)(a: Int, b: Int): Int = { <code removed> }

2) def sum(f: Int => Int, a: Int, b: Int): Int = { <code removed> }

SBT的控制台REPL为它们提供了不同的价值,因此看起来它们是否有所不同:

sum: (f: Int => Int, a: Int, b: Int)Int

sum: (f: Int => Int)(a: Int, b: Int)Int

yan*_*yan 2

Scala 函数支持多个参数列表以帮助柯里化。从第一个示例中,您可以将第一个sum函数视为接受两个整数并返回另一个函数(即curries)的函数,然后该函数可以将Int => Int函数作为参数。

此语法还用于创建外观和行为与新语法相同的函数。例如,def withResource(r: Resource)(block: => Unit)可以调用:

withResource(res) { 
    ..
    ..
}
Run Code Online (Sandbox Code Playgroud)