DarkLite1 DarkLite1 - 3 years ago 156
Java Question

Generics and BiPredicate with incorrect return type

While following a course for

Java 8
we're now onto the topic of
Generics
and
Lambda expressions
. We've been asked to make the following method
Generic
and not
String
only:

public static String betterString(String s1,String s2,IBetterString bs){
if(bs.isBetter(s1, s2)){
return s1;
}else{
return s2;
}
}


What I made of this so far is the following:

public static <T> betterEllement(T s1, T s2, BiPredicate<T, T> bi) {
if (bi.test(s1, s2)) {
return s1;
} else {
return s2;
}
}


But it appears that my
Return type
according to Intellij is incorrect. I don't really understand why that is, because I defined
<T>
as a return type for this method. Sorry if this is a stupid question, I'm just a beginner and would like to understand why it's not correct.

Answer Source

Because you return nothing using your method. <T> define it's a generic Type which is not known yet. That doesnt mean that you return it. You need to add another T which is the generic Type return value.

Its

public static <T> T betterEllement(T s1, T s2, BiPredicate<T, T> bi) {
    if (bi.test(s1, s2)) {
        return s1;
    } else {
        return s2;
    }
}

<T> can also be used if you know the return value but want to define generic arguments.

public static <T> String getStringTest(T test) { 
  if (test.getClass().isInstance(WhatEver.class)) { ....} 
  return "test"; 
} 

You can see it perfectly using a generic Class.

class TestGeneric<T> {
    public T betterElement(T s1) { /** .. **/ return null; }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download