Is there syntactic sugar for binding a value inside an anonymous function in Scala?
-
08-07-2019 - |
Question
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?
Solution
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.
OTHER TIPS
OK, here's the one liner WITH the binding:
({ x:Double => val y = x + x; y * y })(3)
Cheers
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow