Platinum Partner
java,closures,scala

Closures in Java and Scala

People argue that verbose code is easier to understand. Do you agree when reading these two examples, one method in Java, one in Scala?

public List<Item> bought(User user) {
List<Item> result = new ArrayList();
for (Item item : currentItems) {
if (user.bought(item)) {
result.add(item);
}
}
return result;
}
def bought(user: User) = items.filter(user bought _)

If you are familiar with Java, which is more likely then you being familiar with Scala, you may tend to the Java-version. Scala has a different syntax for declaring types and generics, and supports closures, including anonymous parameters (the underscore).

When Closures are introduced in one of the next Java releases, JDK 7 or 8, the example could be rewritten like this:

public List<Item> bought(User user) {
return ListUtils.filter(Item item : items) {
user.bought(item);
}
}

Or with extension methods:

public List<Item> bought(User user) {    
return items.filter(Item item :) { // note the smily! thats what its all about!
user.bought(item);
}
}

And without the curly braces:

public List<Item> bought(User user) {    
return items.filter(Item item :) user.bought(item);
}
The interesting differences between Java with closures and Scala is the static typing: Scala inferences that items are all of type Item, so there is no need to specify that information again. Especially the last example shows that quite clearly.

So, while the current Java Closures specification is a great step in the right direction, lead by Neil Gafter, who is quite the right man for the job, it may not be worth to wait for it, if you have the choice. Its not even sure yet that we'll see that spec implemented in JDK7, and even that is at best one and a half year away.
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}