简体   繁体   English

Scala定义功能标准

[英]Scala define function standard

The following are equivalent: 以下是等效的:

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

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

I am more familiar with the former (coming from Groovy), but the latter form is much more common, AFAIK, the standard way to define a function in Scala. 我更熟悉前者(来自Groovy),但后一种形式更常见,AFAIK,是在Scala中定义函数的标准方法。

Should I forget the past (Groovy) and adopt the 2nd form? 我应该忘记过去(Groovy)并采用第二种形式吗? The 1st form is more natural for me as it looks similar to Groovy/Ruby/Javascript way of defining closures (functions) 第一种形式对我来说更自然,因为它看起来类似于Groovy / Ruby / Javascript定义闭包(函数)的方式

EDIT 编辑
See Zeiger's answer in this thread , for an example where groovy/ruby/javascript closure {=>} syntax seems more natural than () => I assume both can be used interchangeably with same performance, ability to pass around, etc. and that the only difference is syntax 请参阅Zeiger在这个帖子中的答案,例如groovy / ruby​​ / javascript closure {=>}语法似乎比() =>更自然,我认为两者可以互换使用,具有相同的性能,传递能力等等。 唯一的区别是语法

I think that this is the matter of taste (scala styleguide recommends first one). 我认为这是品味问题(scala styleguide推荐的第一个)。 The former one allow you to write multiline (>2 lines in body) functions: 前者允许您编写多行(体内> 2行)函数:

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

Sometimes it is useful 有时它很有用

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. “groovy”版本:一个参数,多个语句。

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

The "scala" version: multiple parameters, one statement. “scala”版本:多个参数,一个声明。

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). 不存在具有单个参数和单个语句的版本,因为它在语法上不有效(即,语法不完全有效)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM