I'm writing a small framework that needs to use instanceof
to know which type of callback is being passed. I already know the disadvantages of instanceof
, but it's used in a third-party library and I can't change that part.
When writing lambdas, and casting them, IntelliJ warns me that the casting is redundant, but actually it is needed (it affects the result), and it works if I explicitly declare the lambda. Do you know if this is a bug, maybe I'm missing something or there is a better way to do this?
Example:
public class Main {
public interface Iface {
String run();
}
public interface IfaceA extends Iface {
}
public interface IfaceB extends Iface {
}
public static void lambdaTest(Iface iface) {
System.out.print(iface.run()+": ");
if (iface instanceof IfaceA) {
System.out.println("IfaceA");
} else if (iface instanceof IfaceB) {
System.out.println("IfaceB");
} else {
System.out.println("Iface");
}
}
public static void main(String[] args) {
lambdaTest((IfaceA)() -> "Casted to A");
lambdaTest((IfaceB)() -> "Casted to B");
lambdaTest(() -> "Not Casted");
IfaceA lambda = () -> "Declared as A";
lambdaTest(lambda);
}
}
And the output is:
Casted to A: IfaceA
Casted to B: IfaceB
Not Casted: Iface
Declared as A: IfaceA
But in IntelliJ I get the warning:
Also tested javac and I don't get any warning:
% javac Main.java -Xlint !2525
In Intellij 2016.1.1 (build 145.597 as of March 29th) no warning is shown. You are probably using older version of Idea and the issue was fixed since then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With