S1612 and casting inside ifPresent()

java
sonarlint

(Ewa Śliwińska) #1

Hi, please consider following case:

public class IfPresent {
    interface Interface {
    }

    class Type1 implements Interface {
    }

    class Type2 implements Interface {
    	void method(final boolean parameter) {
    	}
    }

    public static void main(final String[] args) {
    	final Optional<Boolean> optional = Optional.ofNullable(null);
    	final Interface instance = new IfPresent().new Type1();
        // optional.ifPresent(((Type2) instance)::method);
    	optional.ifPresent(i -> ((Type2) instance).method(i));
	}
}

There is a rule S1612 violation (“Lambdas should be replaced with method references”), but this cannot be replaced - this can be seen by uncommenting the above line - in that case the expression is evaluated before checking if optional is present (from what I understand) and it throws an exception.

version used: SonarLint for Eclipse 3.6