ikts
ikts

Reputation: 45

Generic lambdas not applicable for the arguments

I have the following code

public interface PredicateGeneric<T,Z>{
    boolean compare(T t, Z z);
}

then

PredicateGeneric<Integer,Integer> p= (Integer i, Integer j) -> i>=j;

and finally

public static <T,Z> T getInt(Integer a, Integer b, PredicateGeneric<T,Z> p){
    if(p.compare(a,b)==true){
        return a;
    }else{
        return b;
    }
}

the method is called by

System.out.println(getInt(4,5,p));

in my main method.

I get the following message in Eclipse: "The method compare(T,Z) in the type PredicateGeneric is not applicable for the arguments (Integer, Integer)"

I've had my troubles with generics in the past, so it doesn't surprise me that I've made a mistake, but I cannot find it.

Upvotes: 0

Views: 402

Answers (1)

threaz
threaz

Reputation: 403

Change type declaration to:

public static <T,Z> T getInt(T a, Z b, PredicateGeneric<T,Z> p){
    if(p.compare(a,b)==true){
        return a;
    }else{
        return b;
    }
}

but now you cannot return a or b because their types don't match the declaration. You can either declare this method with both a and b and return value with the same type or think about different return value.

Upvotes: 2

Related Questions