Is there syntactic sugar to bind a value inside an anonymous function in Scala?

Instead of recording

((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 something like this syntactic sugar in Scala?

+6
scala anonymous-function syntactic-sugar
source share
2 answers

Indeed there is: it is called " val ". val

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

Brackets, of course, are optional here, I just prefer their brackets when defining functions (after all, this is not Lisp). The val keyword defines a new binding in the current lexical domain. Scala does not force locals to define their scope, unlike languages โ€‹โ€‹such as Lisp and ML.

Actually, var also works in any field, but he believes that it is bad style to use it.

+14
source share

OK, here is one snapped liner:

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

Greetings

+6
source share

All Articles