# 認識 Lambda/Closure（7）JDK8 Lambda 語法

English

``(Integer x) -> x + 2``

``````public static <A, B, C> Func<A, C> compose(Func<A, B> f, Func<B, C> g) {
return x -> g.apply(f.apply(x));
}``````

``compose((Integer x) -> x + 2, (Integer y) -> y * 3);``

``````compose(
new Func<Integer, Integer>() {
public Integer apply(Integer x) {
return x + 2;
}
},
new Func<Integer, Integer>() {
public Integer apply(Integer y) {
return y * 3;
}
}
);``````
JDK8 Lambda 的通用語法是由參數列、箭號 `token ->` 與函式本體組成。以下是 Lambda 表示式的兩個例子：
``````// 計算 x 與 y 的和
(int x, int y) -> x + y

// 不帶引數，直接傳回整數 42
() -> 42``````

``````// 取得字串並輸出至主控台，沒有傳回值
(String s) -> { out.println(s); }

// 取一個整數並傳回一個整數
(Integer x) -> {
Integer result;
...other statements
...
return result;
};``````

``````public interface Runnable {
void run();
}

public interface Callable<V> {
V call() throws Exception;
}

public interface Comparator<T> {
int compare(T o1, T o2);
}``````

``Func<Integer, Integer> func = x -> x * 2;``

``````public interface Function<P, R> {
R call(P p);
}``````

``Function<Double, Double> f2 = x -> x * 2;``

``````@FunctionalInterface
public interface Func<P, R> {
R apply(P p);
}``````

``````@FunctionalInterface
public interface Function<P, R> {
R call(P p);
R call(P p1, P p2);
}``````

``````import static java.lang.System.out;

public class Hello {
Runnable r1 = new Runnable() {
public void run() {
out.println(this);
}
};
Runnable r2 = new Runnable() {
public void run() {
out.println(toString());
}
};

public String toString() { return "Hello, world!"; }

public static void main(String[] args) {
new Hello().r1.run();
new Hello().r2.run();
}
}``````

``````import static java.lang.System.out;

public class Hello {
Runnable r1 = () -> { out.println(this); };
Runnable r2 = () -> { out.println(toString()); };

public String toString() { return "Hello, world!"; }

public static void main(String[] args) {
new Hello().r1.run();
new Hello().r2.run();
}
}``````