java.util.function 패키지에서는 람다 표현식이나 메서드 참조에 사용할 수 있는 다양한 Functional Interfaces을 제공합니다.
일반적으로 auto-boxing을 피하기 위해 전문화된 인터페이스를 사용하는 것이 좋습니다.
예를 들어 Function<Integer, Foo>보다 IntFunction<Foo>를 사용하는 게 좋습니다.
(^역: auto-boxing - primitive 타입을 boxed type으로 변환해주는 것)
이 규칙은 대안이 존재하는 아래와 같은 인터페이스들을 이용할 때 알림을 울립니다.
| 현재 인터페이스 | 더 나은 인터페이스 |
|---|---|
| Function<Integer, R> | IntFunction |
| Function<Long, R> | LongFunction |
| Function<Double, R> | DoubleFunction |
| Function<Double,Integer> | DoubleToIntFunction |
| Function<Double,Long> | DoubleToLongFunction |
| Function<Long,Double> | LongToDoubleFunction |
| Function<Long,Integer> | LongToIntFunction |
| Function<R,Integer> | ToIntFunction |
| Function<R,Long> | ToLongFunction |
| Function<R,Double> | ToDoubleFunction |
| Function<T,T> | UnaryOperator |
| BiFunction<T,T,T> | BinaryOperator |
| Consumer |
IntConsumer |
| Consumer |
DoubleConsumer |
| Consumer |
LongConsumer |
| BiConsumer<T,Integer> | ObjIntConsumer |
| BiConsumer<T,Long> | ObjLongConsumer |
| BiConsumer<T,Double> | ObjDoubleConsumer |
| Predicate |
IntPredicate |
| Predicate |
DoublePredicate |
| Predicate |
LongPredicate |
| Supplier |
IntSupplier |
| Supplier |
DoubleSupplier |
| Supplier |
LongSupplier |
| Supplier |
BooleanSupplier |
| UnaryOperator |
IntUnaryOperator |
| UnaryOperator |
DoubleUnaryOperator |
| UnaryOperator |
LongUnaryOperator |
| BinaryOperator |
IntBinaryOperator |
| BinaryOperator |
LongBinaryOperator |
| BinaryOperator |
DoubleBinaryOperator |
| Function<T, Boolean> | Predicate |
| BiFunction<T,U,Boolean> | BiPredicate<T,U> |
규칙을 어긴 코드
public class Foo implements Supplier<Integer> { // 규칙을 어긴 코드
@Override
public Integer get() {
// ...
}
}
규칙을 준수한 해결책
public class Foo implements IntSupplier {
@Override
public int getAsInt() {
// ...
}
}
If you like SONARKUBE, don’t forget to give me a star. ![]()