# 高阶函数和lambda表达式

## 高阶函数与 lambda 表达式

### 高阶函数

``````fun <T> lock(lock: Lock, body: () -> T ) : T {
lock.lock()
try {
return body()
}
finally {
lock.unlock()
}
}``````

``````fun toBeSynchroized() = sharedResource.operation()

val result = lock(lock, ::toBeSynchroized)``````

``````val result = lock(lock, {
sharedResource.operation() })``````

``````lock (lock) {
sharedResource.operation()
}``````

``````fun <T, R> List<T>.map(transform: (T) -> R):
List<R> {
val result = arrayListOf<R>()
for (item in this)
return result
}``````

``val doubled = ints.map {it -> it * 2}``

``ints.map {it * 2}``

``strings.filter{ it.length == 5 }.sortedBy{ it }.map{ it.toUpperCase() }``

### 字面函数和函数表达式

``max(strings, {a, b -> a.length < b.length })``

`max` 函数就是一个高阶函数,它接受函数作为第二个参数。第二个参数是一个表达式所以本生就是一个函数，即字面函数。作为一个函数，相当于：

``fun compare(a: String, b: String) : Boolean = a.length < b.length``

### 函数类型

``````fun max<T>(collection: Collection<out T>, less: (T, T) -> Boolean): T? {
var max: T? = null
for (it in collection)
if (max == null || less(max!!, it))
max = it
return max
}``````

``val compare: (x: T,y: T) -> Int = ...``

### 函数文本语法

``val sum = {x: Int,y: Int -> x + y}``

``val sum: (Int, Int) -> Int = {x, y -> x+y }``

``ints.filter {it > 0}//这是 (it: Int) -> Boolean  的字面意思``

### 函数表达式

``fun(x: Int, y: Int ): Int = x + y``

``````fun(x: Int, y: Int): Int {
return x + y
}``````

``ints.filter(fun(item) = item > 0)``

### 闭包

``````var sum = 0

ints.filter{it > 0}.forEach {
sum += it
}
print(sum)``````

### 函数表达式扩展

``val sum = fun Int.(other: Int): Int = this + other``

``sum : Int.(other: Int) -> Int``

``1.sum(2)``