Search code examples
javalambdatuplesjava-streamkeyvaluepair

Type problems with tuples & streams


I have my own implementation for a few tuples, here's the gist of the code for pair:

public class Pair<A, B>  extends Tuple implements Serializable{
    ...
    public Pair(A a,B b){
        this.a=a;
        this.b=b;
    }
    ...
    public <T> Pair<T,B> mapA(Function<A,T> fun){
        return new Pair<T,B>(fun.apply(a),b);
    }
    ...
}

For some weird reason the following code does not work and the compiler seems to think that the resulting pair from the first mapping is <Object,String>.

List<Pair<String,String>> pairs = ...;
pairs
.stream()
.map(p->mapA(s->s.trim())
.map(p->mapA(s->s.toUpperCase()) //does not recognize a as a string
...

Could this be also Eclipse acting up? Running Eclipse Luna fwiw which seems to do a shitty job in general in determining generic types from functional interfaces.

EDIT: full example as requested

public class Pair<A, B> implements Serializable{
    public final A a;
    public final B b;

    public Pair(A a,B b) {
        this.a = a;
        this.b = b;
    }

    public <T> Pair<T,B> mapA(Function<A,T> fun){
        return new Pair<T,B>(fun.apply(a),b);
    }

}


List<Pair<String,String>> pairs = new ArrayList<>();
pairs.add(new Pair<String,String>("foo","bar"));
pairs.stream()
.map(p->p.mapA(s->s.trim()))
.map(p->p.mapA(s->s.toUpperCase()))
.collect(Collectors.toList());

Solution

  • Updated to Eclipse Mars and the issue is completely gone.