user1511417
user1511417

Reputation: 1940

Java lambda-expressions with miscellaneous operands

This lambda expressions work perfectly for math-operations with two operands (a and b).

public class Math {
  interface IntegerMath {
    int operation(int a, int b);       
  }

  private static int apply(int a, int b, IntegerMath op) {
    return op.operation(a, b);
  }

  public static void main(String... args) {
    IntegerMath addition = (a, b) -> a + b;
    IntegerMath subtraction = (a, b) -> a - b;
    System.out.println("40 + 2 = " + apply(40, 2, addition));
    System.out.println("20 - 10 = " + apply(20, 10, subtraction));

  }
}

How can you enhance this class with possible unary operations for example

IntergerMath square = (a) -> a * a;

?

Upvotes: 2

Views: 386

Answers (3)

user1511417
user1511417

Reputation: 1940

You'll need a new interface for unary operations.

public class Math {
  interface BinMath {
    int operation(int a, int b);

  }

  interface UnMath {
    int operation(int a);

  }

  private static int apply(int a, int b, BinMath op) {
    return op.operation(a, b);
  }

  private static int apply(int a, UnMath op) {
    return op.operation(a);
  }

  public static void main(String... args) {
    BinMath addition = (a, b) -> a + b;
    BinMath subtraction = (a, b) -> a - b;
    UnMath square = (a) -> a * a;

    System.out.println("40 + 2 = " + apply(40, 2, addition));
    System.out.println("20 - 10 = " + apply(20, 10, subtraction));
    System.out.println("20² = " + apply(20, square));

  }
}

Upvotes: 0

assylias
assylias

Reputation: 328735

You can't do it because the square method does not have the same signature.

Note that you could also use an IntBinaryOperator and an IntUnaryOperator (which as you can notice are completely separate) instead of creating your own interfaces.

Upvotes: 2

Eran
Eran

Reputation: 393946

You can't do it with IntegerMath, since it's a functional interface whose single abstract method takes two int arguments. You'll need a new interface for unary operations.

BTW, you don't have to define those interfaces yourself. java.util.function contains interfaces you can use, such as IntUnaryOperator and IntBinaryOperator.

Upvotes: 3

Related Questions