Java 函數語言程式設計 - 函式
函式是一段執行特定任務的語句塊。函式接受資料,處理資料並返回結果。編寫函式的主要目的是支援可重用性的概念。一旦編寫了函式,就可以輕鬆地呼叫它,而無需一遍又一遍地編寫相同的程式碼。
函數語言程式設計圍繞一等函式、純函式和高階函式展開。
一等函式是可以像字串、數字一樣用作一等實體的函式,可以作為引數傳遞,可以作為返回值,也可以賦值給變數。
高階函式是可以接受函式作為引數和/或可以返回函式的函式。
純函式是在執行過程中沒有副作用的函式。
一等函式
一等函式可以像變數一樣對待。這意味著它可以作為引數傳遞給函式,可以被函式返回,也可以被賦值給變數。Java 使用 lambda 表示式支援一等函式。lambda 表示式類似於匿名函式。請參見下面的示例:
public class FunctionTester {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
SquareMaker squareMaker = item -> item * item;
for(int i = 0; i < array.length; i++){
System.out.println(squareMaker.square(array[i]));
}
}
}
interface SquareMaker {
int square(int item);
}
輸出
1 4 9 16 25
這裡我們使用 lambda 表示式建立了 square 函式的實現,並將其賦值給變數 squareMaker。
高階函式
高階函式要麼將函式作為引數,要麼返回函式。在 Java 中,我們可以傳遞或返回 lambda 表示式來實現此功能。
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
Function<Integer, Integer> square = t -> t * t;
Function<Integer, Integer> cube = t -> t * t * t;
for(int i = 0; i < array.length; i++){
print(square, array[i]);
}
for(int i = 0; i < array.length; i++){
print(cube, array[i]);
}
}
private static <T, R> void print(Function<T, R> function, T t ) {
System.out.println(function.apply(t));
}
}
輸出
1 4 9 16 25 1 8 27 64 125
純函式
純函式不會修改任何全域性變數或修改作為引數傳遞給它的任何引用。因此它沒有副作用。當使用相同的引數呼叫時,它始終返回相同的值。此類函式非常有用並且是執行緒安全的。在下面的示例中,sum 是一個純函式。
public class FunctionTester {
public static void main(String[] args) {
int a, b;
a = 1;
b = 2;
System.out.println(sum(a, b));
}
private static int sum(int a, int b){
return a + b;
}
}
輸出
3
廣告