Casting in lambdas marked as redundant in IntelliJ

I am writing a small structure that instanceof should use to find out what type of callback is being passed. I already know the flaws of instanceof , but it is used in a third-party library, and I cannot change this part.

When I write lambdas and throw them away, IntelliJ warns me that casting is redundant, but actually it is necessary (it affects the result), and it works if I explicitly declare the lambda. Do you know that this is a mistake, maybe I missed something or is there 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 result:

 Casted to A: IfaceA Casted to B: IfaceB Not Casted: Iface Declared as A: IfaceA 

But in IntelliJ I get a warning:

enter image description here

enter image description here

Javac is also tested, and I am not getting a warning:

  % javac Main.java -Xlint !2525 
+5
source share
1 answer

Intellij 2016.1.1 (build 145.597 dated March 29) does not display a warning. You are probably using an older version of Idea, and the problem has been fixed since then.

enter image description here

+4
source

All Articles