Generic type instantiation and Lambdas

Nadia Rodriguez :

I am working with anonymous functions and functional interfaces, I have one functional interface that takes two objects of same type and returns true or false.

package elementutils;
@FunctionalInterface
public interface TwoElementPredicate <T> {
    public boolean compare(T a, T b);
    }

I use the functional interface in another class to get the "better element" using anonymous functions, the method betterElement takes two objects and the instance of the functional interface. Then i should be able to create lambdas to compare two objects of the same type in the main.

package elementutils;

public class ElementUtils <T> {
    public  T  betterElement(T a, T b, TwoElementPredicate elements){
    if (elements.compare(a, b) == true) {
        return a;
    }else {
        return b;
    }
    }
    public static void main(String[] args) {
        //String x= ElementUtils.betterElement("java", "python", (a, b) -> a.length() < b.length());
        //int y= ElementUtils.betterElement(2, 3, (a, b) -> a > b);
        //double z= ElementUtils.betterElement(2.5, 3.7, (a, b) -> a > b);
        // all this give errors

    }

}

The functions should take any object as long as they are from the same type. I thought I could achieve that using generic classes but when I instantiate the lambdas it seems that the elements are always of type object so I cannot use length() and cannot assigne them to a String for example.

I hope I explained myself correctly, any help will be highly appreciated.

user7 :

You are missing the type parameter T on TwoElementPredicate and hence you are using a raw type

You need to declare the parameter elements as of type TwoElementPredicate<T>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89811&siteId=1