3

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.

Should I forget the past (Groovy) and adopt the 2nd form? The 1st form is more natural for me as it looks similar to Groovy/Ruby/Javascript way of defining closures (functions)

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

Community
  • 1
  • 1
virtualeyes
  • 11,147
  • 6
  • 56
  • 91

2 Answers2

2

I think that this is the matter of taste (scala styleguide recommends first one). The former one allow you to write multiline (>2 lines in body) functions:

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

Sometimes it is useful

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • You can write multiline functions with the second form as well: `val f = (i: Int) => { ... multiline body ... }` – Greg Campbell Apr 30 '12 at 16:01
  • +1, yes, that is "exactly" the syntax I have grown used to on the dynamic side of the fence. – virtualeyes Apr 30 '12 at 16:02
  • @GregCampbell yes, but in scala doc, the one op provided and one you've writed treats as different types – om-nom-nom Apr 30 '12 at 16:03
  • 1
    @GregCampbell cookie monster's version is cleaner, IMO, for multi-line. Of course, my eyes filter in favor of val f = {...}. Will likely change the more I work with Scala – virtualeyes Apr 30 '12 at 16:05
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).

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681