ClassCastLambdaUsage
SUGGESTION
Simplification
Summary
Prefer
Class::cast
method reference over equivalent lambda expression
Suppression
Suppress false positives by adding the suppression annotation
@SuppressWarnings("ClassCastLambdaUsage")
to the enclosing element.Disable this pattern completely by adding
-Xep:ClassCastLambdaUsage:OFF
as compiler argument. Learn more.
Samples
Replacement
Shows the difference in example code before and after the bug pattern is applied.
import java.util.stream.Stream;
class A {
void m() {
- Stream.of(1).map(i -> (Integer) i);
+ Stream.of(1).map(Integer.class::cast);
}
}
Identification
Shows code lines which will (not) be flagged by this bug pattern.
A //BUG: Diagnostic contains:
comment is placed above any violating line.
import com.google.common.collect.ImmutableSet;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class A {
<T> void m() {
Number localVariable = 0;
Stream.of(0).map(i -> i);
Stream.of(1).map(i -> i + 1);
Stream.of(2).map(Integer.class::cast);
Stream.of(3).map(i -> (Integer) 2);
Stream.of(4).map(i -> (Integer) localVariable);
// XXX: Ideally this case is also flagged. Pick this up in the context of merging the
// `ClassCastLambdaUsage` and `MethodReferenceUsage` checks, or introduce a separate check that
// simplifies unnecessary block lambda expressions.
Stream.of(5)
.map(
i -> {
return (Integer) i;
});
Stream.<ImmutableSet>of(ImmutableSet.of(6)).map(s -> (ImmutableSet<Number>) s);
Stream.of(ImmutableSet.of(7)).map(s -> (ImmutableSet<?>) s);
Stream.of(8).reduce((a, b) -> (Integer) a);
IntStream.of(9).mapToObj(i -> (char) i);
Stream.of(10).map(i -> (T) i);
// BUG: Diagnostic contains:
Stream.of(11).map(i -> (Integer) i);
}
}