On Oct 23, 2009, at 2:31 AM, jlist9 wrote:
>> Regarding () and {} BTW, you can replace a single-argument argument
>> list with {}, e.g.
>>
>> def myFunction(a: String): Unit = println(a)
>>
>> myFunction("foobar")
>> myFunction { "foobar" }
>
> I find the following three lines of code do the same thing.
> Thanks for your explanation again. I now understand
> why the first and second line are equivalent. (But why
> does Scala allow {} here? Isn't () good enough?)
I find it's good when you're doing a block-like thing where it really
expects a single value. Most often I use this with functions that do
something "scoped", e.g. acquire a resource and release it, or set
some kind of semi-global variable temporarily (RequestVar.doWith,
ThreadGlobal.doWith, for example).
> I'm not sure what the {} does in the third line, though.
>
> args.foreach{ arg => greeting += (arg + " ") }
> args.foreach( arg => greeting += (arg + " ") )
> args.foreach( arg => { greeting += (arg + " ") } )
The {}s in this case would allow you to have multiple statements
there. To contrast:
args.map(arg => println(arg); arg.length) // won't compile
args.map { arg => println(arg); arg.length } // compiles
args.map(arg => { println(arg); arg.length }) // compiles
I personally prefer the last form because my editor will happily eat
it and I get some consistency when there's arguments before the
function argument. Of course, this is an aesthetic thing, I'm sure
other people prefer the parenless form.
-Ross
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Lift" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/liftweb?hl=en
-~----------~----~----~----~------~----~------~--~---