Java 8:
public void filter(Filter f, List<Integer> integerList) { for (Integer i : integerList) { if (f.test(i)) { System.out.println(i); } } } // 定義一個 SAM interface Filter { boolean test(int x); } public void lambdaDemo() { filter((x) -> x % 2 == 1, Arrays.asList(1, 2, 3, 4, 5, 6, 7)); }
Java 在一個擁有兩個方法(不含默認方法)的接口中,是不可以使用 Lambda 表達式的,當一個接口中只有一個抽象方法,即達成了SAM(Single Abstract Method)條件時,Lambda表達式纔可以使用。
Kotlin:
fun filter(f: (Int) -> Boolean, integerList: List<Int>) { for (i in integerList) { if (f(i)) { println(i) } } } fun lambdaDemo() { filter({ x -> x % 2 == 1 }, Arrays.asList(1, 2, 3, 4, 5, 6, 7)) }
在 Kotlin 中,函數 f:(Int)->Boolean 也是一種類型,可以像普通的參數變量一樣,在函數入參中傳遞,當然也可以返回一個函數。
小結
相比之下,Kotlin 對函數式編程的支持更加自然優雅。