以函數(shù)作為參數(shù)或返回函數(shù)的函數(shù)被稱為高階函數(shù)
fun numTest(num: Int, bool: (Int) -> Boolean): Int {
return if (bool(num)) num else 0
}
//invoking
println(numTest(5) { it > 5 })//print 0
println(numTest(8) { it > 5 })//println 8
fun numCompare(num1: Int, num2: Int, compare: (a: Int, b: Int) -> Boolean): Int {
return if (compare(num1, num2)) num1 else num2
}
fun biggerNum(a: Int, b: Int) = a > b
fun smallNum(a: Int, b: Int) = a < b
//invoking
println(numCompare(5, 8, ::biggerNum))//print 8
println(numCompare(1, 2, ::smallNum))//print 1
println(numCompare(10, 12) { a, b ->
a == b
})//print 12
Android開發(fā)中RecyclerView的Item點擊事件
private var listener: ((Int, String) -> Unit)? = null
fun setOnClickListener(l: (position: Int, content: String) -> Unit) {
listener = l
}
//invoking
setOnClickListener { position, content ->
println("$position $content")
}
listener?.invoke(5, "China")//print 5 China
fun <T> lock(lock: Lock, body: () -> T): T {
lock.lock()
try {
return body()
} finally {
lock.unlock()
}
}