Funny coincidence: yesterday in work I was trying to find a way to express something simple enough in Java: I want a method map that takes a generic collection and return a collection of the same type (that is, passing a List should return a List, passing a Set should return a Set) with a different generic type. In Java you can have:
public <T1,T2> Collection<T2> map(Collection<T1> c,Mapper<T1,T2>
Where Mapper is an interface defining the method T2 map(T1 o);
There is no way I think in Java to express that if you pass a subclass of collection you get the same subclass back.
I tried things like <T1,T2,C extends Collection,C1 extends C<T1>,C2 extends C<T2> and other crazy things that my compiler didn't appreciate.
You have to duplicate methods, and that's what we've done in work:
public <T1,T2> List<T2> map(List<T1> c,Mapper<T1,T2>
public <T1,T2> Set<T2> map(Set<T1> c,Mapper<T1,T2>
And of course a colleague needed a Vector because he was using an old library still using Vectors...
And then today I found that blog post, that point to that PDF document. Apparently you can do this kind of things in Scala and Haskell... Do I need to convince my company to move to Scala?
2 comments:
hello sir you have a nice blog can please give me some tips for blogging. i too have a programming blog please visit it at http://solvedprograms.blogspot.in/
anuj
Post a Comment