Hungry Blue Dev
Hungry Blue Dev

Reputation: 1325

Trouble with Java 8 lambda expressions

I have an interface Operation a follows:

interface Operation {
    public double calc(double a, double b);
}

And I use it in an enum.

public enum Operations {

    POWER("^", new Operation(){
        public double calc(double a, double b) {
            return Math.pow(a, b);
        }
    }),
    MULTIPLICATION("*", new Operation(){
        public double calc(double a, double b) {
            return a * b;
        }
    }),
    //...

    private String op;
    private Operation calc;

    public Operations(String op, Operation calc) {
        this.op = op;
        this.calc = calc;
    }
}

I want to shorten my code using lambda expressions but I can't seem to get the syntax right. The oracle tutorials are a bit too complicated for me. Could some one explain it to me in a simple manner?

EDIT: I've tried:

POWER ("^", (double a, double b) -> Math.pow(a,b)), and so on, but it doesn't compile.


Fixed:

import java.util.function.*;
public enum Operations {
    POWER("^", Math::pow),
    MULTIPLICATION("*", (double a,double b)->a*b),
    private final String op;
    private final DoubleBinaryOperator calc;
    Operations(String op, DoubleBinaryOperator calc) {
        this.op = op;
        this.calc = calc;
    }
    DoubleBinaryOperator getCalc() {
        return calc;
    }
}

Upvotes: 2

Views: 1096

Answers (3)

Bukhari Syed
Bukhari Syed

Reputation: 499

(a, b) -> Math.pow(a, b)

The Math.pow returns a double type value. If lambda accepts int type cast it like

(a, b) -> (int) Math.pow(a, b) ;

Upvotes: 0

Boris the Spider
Boris the Spider

Reputation: 61128

Delete the interface Operation as this is just a DoubleBinaryOperator

public enum Operations {

    POWER("^", Math::pow),
    MULTIPLICATION("*", (a, b) -> a * b);

    private String op;
    private DoubleBinaryOperator calc;

    Operations(String op, DoubleBinaryOperator calc) {
        this.op = op;
        this.calc = calc;
    }
}

You can use a method reference for Math.pow as this already follows the required signature.

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213193

Operation being a functional interface, the expression:

new Operation(){
    public double calc(double a, double b) {
        return Math.pow(a, b);
    }
}

can be replaced with the following lambda expression:

(a, b) -> Math.pow(a, b)  

or the method reference:

Math::pow

With this, your enum will become:

public enum Operations {

    POWER("^", Math::pow),
    MULTIPLICATION("*", (a, b) -> a * b);

    private String op;
    private Operation calc;

    public Operations(String op, Operation calc) {
        this.op = op;
        this.calc = calc;
    }
}

Upvotes: 9

Related Questions