2015-11-11 40 views
2

這個lambda表達式適用於具有兩個操作數(a和b)的數學運算。帶有其他操作數的Java lambda表達式

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)); 

    } 
} 

你怎麼能增強這種類例如

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

可能一元操作?

回答

3

你不能用IntegerMath這樣做,因爲它是一個功能接口,其單個抽象方法需要兩個參數int。您將需要一個新的界面進行一元操作。

順便說一句,你不必自己定義這些接口。 java.util.function包含您可以使用的接口,例如IntUnaryOperatorIntBinaryOperator

2

你不能這樣做,因爲square方法沒有相同的簽名。

請注意,您也可以使用IntBinaryOperatorIntUnaryOperator(您可以注意到它們完全分開),而不是創建自己的接口。

0

您將需要一個用於一元操作的新界面。

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)); 

    } 
}