Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 564
virtualeyes Avatar asked Jul 11 '26 00:07

virtualeyes


1 Answers

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

like image 165
om-nom-nom Avatar answered Jul 13 '26 14:07

om-nom-nom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!