3

以下是等价的:

scala> val f1 = {i: Int => i == 1}
f1: Int => Boolean = <function1>

scala> val f2 = (i: Int) => i == 1
f2: Int => Boolean = <function1>

我更熟悉前者(来自 Groovy),但后一种形式更常见,AFAIK,在 Scala 中定义函数的标准方法。

我应该忘记过去(Groovy)并采用第二种形式吗?第一种形式对我来说更自然,因为它看起来类似于 Groovy/Ruby/Javascript 定义闭包(函数)的方式

编辑
参见 Zeiger 在这个线程中的回答,例如,groovy/ruby/javascript 闭包{=>}语法似乎比() =>我假设两者可以互换使用更自然,具有相同的性能、传递能力等,唯一的区别是语法

4

2 回答 2

2

Actually, both versions are simplified forms of the "full" version.

Full version: multiple parameters, multiple statements.

scala> val f0 = { (x: Int, y: Int) => val rest = x % y; x / y + (if (rest > 0) 1 else 0) }
f0: (Int, Int) => Int = <function2>

The "groovy" version: one parameter, multiple statements.

scala> val f1 = { x: Int => val square = x * x; square + x }
f1: Int => Int = <function1>

The "scala" version: multiple parameters, one statement.

scala> val f2 = (x: Int, y: Int) => x * y
f2: (Int, Int) => Int = <function2>

A version with a single parameter and a single statement does not exist, because it is not syntactically valid (ie, the grammar for that doesn't quite work).

于 2012-04-30T19:39:40.990 回答
2

我认为这是品味问题(scala styleguide推荐第一个)。前一个允许您编写多行(正文中> 2行)函数:

val f1 = { i: Int =>
  val j = i/2
  j == 1
}

有时它很有用

于 2012-04-30T15:53:36.793 回答