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?

Was it helpful?

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
scroll top