This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static <T,U> List<U> map(List<T> list,{T=>U} transform) { | |
List<U> result = new ArrayList<U>(list.size()); | |
for (T t : list) { result.add(transform.invoke(t)); } | |
return result; | |
} | |
public static void main(String[] args) { | |
List<Color> colors = map(Arrays.asList(Flavor.values()), { Flavor f => f.color }); | |
System.out.println(colors.equals(Arrays.asList(Color.values()))); | |
} |
I found this code sample in a blog post by Kirilli Grouchnikov. He compared this closure example from Neil Gafter to a none-closure version.To be honest, a couple of weeks ago, when I first read that blog post, I didn't feel comfortable looking at this code. I couldn't imagine ever writing or maintaining something like that. Somehow my view has shifted and I'm beginning to see what this is all about.Another situation that got me thinking was Item 22 of "Effective Java". Joshua Bloch explains how to substitute C's function pointers with a Java implementation of the strategy pattern. When I read that item, for a moment, I thought: isn't that more complicated and more verbose than a function pointer. I tossed that thought aside, since having statically checked interfaces were and probably are still preferable to me. I'm really excited where this is going and just enjoying growing up.
0 comments:
Post a Comment