(부록) 람다(lambda)
함수형 인터페이스란
// 함수형 인터페이스 정의
@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
}람다(lambda)란
람다 어원
자바의 람다
java.util.function패키지의 주요 함수형 인터페이스:
Last updated
// 함수형 인터페이스 정의
@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
}
java.util.function패키지의 주요 함수형 인터페이스:
Last updated
// 매개변수가 없고, "Hello, World!"를 출력
Runnable r = () -> System.out.println("Hello, World!");
// 매개변수가 하나인 경우, 타입을 명시적으로 지정할 수 있음
Consumer<String> c = (String x) -> System.out.println(x);
// 타입 추론이 가능하면 타입을 생략할 수 있음
Consumer<String> c2 = x -> System.out.println(x);
// 두 개의 매개변수를 받아서 더하는 함수
BinaryOperator<Integer> add = (a, b) -> a + b;
// 두 개의 매개변수를 받아서 더하는 함수 (타입 명시)
BinaryOperator<Integer> addExplicit = (Integer a, Integer b) -> a + b;class OperationConstant {
companion object {
val PLUS = "+"
val MINUS = "-"
val MULTIPLE = "*"
val DIVIDE = "/"
val SYMBOLS = listOf(PLUS, MINUS, MULTIPLE, DIVIDE)
val SPACE = " "
val EMPTY = ""
}
}
enum class Operation(val symbol: String, val calculation: (Long, Long) -> Long) {
PLUS(OperationConstant.PLUS, { num1: Long, num2: Long -> num1 + num2 }),
MINUS(OperationConstant.MINUS, { num1: Long, num2: Long -> num1 - num2 }),
MULTIPLE(OperationConstant.MULTIPLE, { num1: Long, num2: Long -> num1 * num2 }),
DIVIDE(OperationConstant.DIVIDE, { num1: Long, num2: Long -> num1 / num2 });
companion object {
fun findCalculation(symbol: String?): Operation {
require(symbol != null && symbol != OperationConstant.SPACE && symbol != OperationConstant.EMPTY) {
"null, 빈 문자열, 공백은 허용되지 않습니다."
}
require(values().map { it.symbol }.contains(symbol)) {
"사칙연산 기호가 아닙니다."
}
return values().first() { it.symbol == symbol }
}
}
}