James Iry
Posts: 85
Nickname: jiry
Registered: Nov, 2007
|
|
Re: New Control Structures for Java
|
Posted: Nov 6, 2008 8:20 AM
|
|
Howard, I want to make a small correction before answering your question.
If you can read it in your code {x => x + y}, then it's a lambda (or "anonymous function"), not a closure. A closure is a runtime value that has captured bindings from the lexical environment. The lambda I just gave gives rise to many different closures - one distinct closure per captured value of y.
The relationship between lambda and closure is exactly the relationship between class and object.
Where I'm going with that distinction is that Scala by-name parameters ( => Foo) are indeed implemented exactly the same way that no-arg closures are implemented. The runtime object is an instance of a trait with an apply method. So it's a bit inaccurate to say that Scala has "two kinds of closure." But, more importantly, you cannot treat by-name parameters the same way you treat closures. They're just by-name parameters. You don't type in a lambda to create them and you don't apply them to evaluate them. You use them much like by-need parameters do in Haskell, except that they aren't memoized.
Finally, before I move on, Scala lets you nest classes, traits, and object literals. Instances of these all capture bindings from their lexical environment (even mutable references). So if you want to go down the route of saying that lambdas and by-name parameters create two different kinds of closure then we might as well admit all the above and say that Scala has a huge zoo of different types of closure.
Now to the heart of your question: where are lambdas superior to inner classes? The answer depends very much on your definition of superior. I think implementing an entire parser combinator library in a single page of code is superior to implementing it in page after page of anonymous inner classes. I think thinking of functions as ordinary values liberates your view of the world. I think most object oriented programmers over-emphasize mutation precisely because it's syntactically easier to do mutation than to write the equivalent of a higher order functions. Why doesn't the Java standard collection library have map,filter, monadic bind etc? Precisely because it's easier to do that stuff in a loop when you don't have lambdas.
|
|