views:

197

answers:

2

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?

+6  A: 

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.

Daniel Spiewak
Thanks :) I thought I had tried that, but I must have gotten the syntax wrong. Is there a way to have it all in one line?
namin
@Germán has the one-line version.
Daniel Spiewak
+4  A: 

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

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

Cheers

Germán