Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there syntactic sugar for binding a value inside an anonymous function in Scala?

Instead of writing

((x: Double) => (((y: Double) => y*y))(x+x))(3)

I would like to write something like

((x: Double) => let y=x+x in y*y)(3)

Is there anything like this sort of syntactic sugar in Scala?

like image 669
namin Avatar asked Nov 18 '08 08:11

namin


2 Answers

Indeed there is: it's called "val". :-)

({ x: Double =>
  val y = x + x
  y * y
})(3)

The braces are of course optional here, I just prefer them to parentheses when defining functions (after all, this isn't Lisp). The val keyword defines a new binding within the current lexical scope. Scala doesn't force locals to define their own scope, unlike languages such as Lisp and ML.

Actually, var also works within any scope, but it's considered bad style to use it.

like image 110
Daniel Spiewak Avatar answered Nov 19 '22 06:11

Daniel Spiewak


OK, here's the one liner WITH the binding:

 ({ x:Double => val y = x + x; y * y })(3)

Cheers

like image 33
Germán Avatar answered Nov 19 '22 05:11

Germán