Edit
ok, great feedback here, got me pointed in the right direction. Use case for invoking anonymous closure is in Scalatra routing layer. I have a bunch of routes that are grouped together under various types, in this example, requests common to teams:
class Router {
type TeamType <: _Controller with _Team
get("""(schedules|rosters|teamresults|teamstats)/\d{8}""".r) {
val clazz :: date = captures
val obj = (clazz match {
case "schedules" => new RosterController
case "rosters" => new ScheduleController
}).asInstanceOf[TeamType]
obj.show(date)
}
}
By wrapping the match expression in a a self-invoked anonymous closure, we avoid tacking on "FooController.asInstanceOf[TeamType]" to each matched case, and instead do the type cast on returned instance, maintaining immutability in the process (i.e. could not "val obj = clazz match {...}" followed by type cast as obj has already been val'd)
I believe that this is as short-form as one can get when creating object instances based on string class name. Of course, saying that, there is likely an FP approach that does the job with even greater concision...
Anyway cool stuff, was missing anonymous closures from Groovy, and now I discover Scala has that covered as well ;-)
Original
Not sure how to pull this off in Scala. In Groovy you can both define and invoke an anonymous closure like so:
{String s-> println(s) }("hello")
What is the equivalent in Scala? Also, rather than returning Unit, how would one specify a return type?
Thanks