Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting in lambdas, marked as redundant in IntelliJ

Tags:

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:

enter image description here

enter image description here

Also tested javac and I don't get any warning:

 % javac Main.java -Xlint                                                                                                                                                                          !2525
like image 982
Guillermo Merino Avatar asked Apr 28 '16 11:04

Guillermo Merino


1 Answers

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.

enter image description here

like image 146
Vojtech Ruzicka Avatar answered Oct 13 '22 01:10

Vojtech Ruzicka