Skip to content

[Effective Java] Item 42. DoubleBinaryOperator #29

@taxol1203

Description

@taxol1203

코드 42-4에서 DoubleBinaryOperator의 역할이 정확하게 잘 이해가 가지 않네요,

Operation 클래스의 apply() 메서드는 DoubleBinaryOperator의 인스턴스 op를 호출하여 계산하고 리턴하는데,
이 op와 람다 함수의 관계를 모르겠습니다.

혹시 이 Enum 클래스의 동작 과정과 함께 설명 부탁드려도 될까요?

public class item42_Operation {
	enum Operation {
	    PLUS("+", (x, y) -> x + y),
	    MINUS("-", (x, y) -> x - y),
	    TIMES("*", (x, y) -> x * y),
	    DIVIDE("/", (x, y) -> x / y);

	    private final String symbol;
	    private final DoubleBinaryOperator op;

	    Operation(String symbol, DoubleBinaryOperator op) {
	        this.symbol = symbol;
	        this.op = op;
	    }

	    @Override
	    public String toString() { return symbol; }

	    public double apply(double x, double y) {
	        return op.applyAsDouble(x, y);  // ???
	    }
	}

    public static void main(String[] args) {
        // 사용은 아래와 같이
        double num = Operation.PLUS.apply(2, 3);
        System.out.println(num);
	}
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions