# 在下函数式编程有何贵干

## 特性

### 函数是一等公民

Scala

``````val add = (x: Int, y: Int) => x + y

Java

``````interface Adder {
}

### 闭包

Scala

``````var factor = 10
factor = factor * 10
val multiplier = (x: Int) => x * factor``````

Java

``````int factor = 10;
//        factor = factor * 10;
Multiplier multiplier = (x) -> x * factor;``````

### 惰性求值 Lazy Evaluation

Scala

``````lazy val lazyField = {
var sum = 0
for (i <- 1 to 100) {
sum += i
}
sum
}``````

Java

``````Supplier<Integer> lazyField = () -> {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
};``````

Java 虽然在语言层面没有提供该功能，但是可以通过 Java 8 提供的 `Supplier` 接口来实现同样的功能。

### 尾递归 Tail Recursion

``````def addOne(i: Int) {
if (i > 3) return
println(s"before \$i")
println(s"after \$i")
}``````

``````before 1
before 2
before 3
after 3
after 2
after 1``````

``line xxx, call addOne -> addOne(1) -> addOne(2) -> addOne(3) -> addOne(2) -> addOne(1) -> line xxx``

``line xxx, call addOne -> addOne(1) -> addOne(2) -> addOne(3) -> line xxx``

### 纯函数 Pure Function

``````def add(x: Int, y: Int) = x + y

def clear(list: mutable.MutableList): Unit = {
list.clear()
}

def random() = Random.nextInt()
``````

### 高阶函数 High-Order Function

``````def assert(predicate: () => Boolean) =
if (!predicate())
throw new RuntimeException("assert failed")

assert(() => 1 == 2)``````

``````def create(): Int => Int = {
val factor = 10
(x: Int) => x * factor
}``````

### 集合操作 Collection

Scala

``````val list = List(1, 2, 3)
list.map(i => {
println(s"before \$i")
i * 2
}).map(i => i + 1)
.foreach(i => println(s"after \$i"))``````

``````before 1
before 2
before 3
after 3
after 5
after 7``````

Java

``````List<Integer> list = new ArrayList<>();
list.stream()
.map(i -> {
System.out.println("before " + i);
return i * 2;
}).map(i -> i + 1)
.forEach(i -> System.out.println("after " + i));``````

``````before 1
after 3
before 2
after 5
before 3
after 7``````

Scala 中一个操作中的所有数据完成处理后才流向下一个操作，可以看做每个操作都是一个关卡。而 Java 则是默认使用了惰性求值的方式，并且概念非常类似 Spark。其各种集合操作主要分为两种： transformation 和 action。transformation 即转换操作，所有返回 `Stream` 对象的函数都是 transformation 操作，该操作不会立即执行，而是将执行步骤保存在 `Stream` 对象中。action 即执行操作，action 没有返回值，调用后会立即执行之前 `Stream` 对象中保存的所有操作。 `map()` 这样的就是 transformation 操作，`forEach()` 就是 action 操作。

### 柯理化 Currying

``def minus(x: Int, y: Int) = x - y``

``def minusCurrying(x: Int)(y: Int) = x - y``

``````minus(5, 3)
minusCurrying(5)(3)``````

### 部分应用 Function Partial Application

``def show(prefix: String, msg: String, postfix: String) = prefix + msg + postfix``

``````val applyPrefix = show("(", _: String, _: String)
println(applyPrefix("foo", ")")) //  (foo)

val applyPostfix = show(_: String, _: String, ")")
println(applyPostfix("(", "bar")) //  (bar)``````

### 偏函数 Partial Function

``````val isEven: PartialFunction[Int, String] = {
case x if x != 0 && x % 2 == 0 => x + " is even"
}``````

``````val isOdd: PartialFunction[Int, String] = {
case x if x % 2 != 0 => x + " is odd"
}
val other: PartialFunction[Int, String] = {
case _ => "else"
}
val partial = isEven orElse isOdd orElse other
println(partial(3)) //  3 is odd
println(partial(0)) //  else``````

### 尾声

• 分享主题1：JVM上的高性能Reative工具Vert.x3介绍

• 分享主题1：Vert.x在maxleap的最佳实践

• 分享主题1：Vert－web注解封装

92 人关注
75 篇文章