前言
以后要戒掉坏习惯,在自己不知道做什么的时候就看书写博客
高阶函数
高阶函数就是把函数作为参数或者是返回值的函数,这是kotlin支持函数式编程的缘故。
- 函数引用
::println 通过::来获取函数的引用
//通过::获取函数的应用之后传递给高阶函数
args.forEach(::println)
- 引用类中的成员方法
class Hello {
fun world() {
println("Hello World")
}
}
/ / 拿到成员方法的引用
val helloworld = Hello::world
- 返回一个receiver的方式
val pdfprintln = PdFPrintln()
args.forEach(pdfprintln::println)//函数引用包级函数
class PdFPrintln {
fun println(any: Any) {
kotlin.io.println(any)
}
}
常用高阶函数
ForEach() 高阶函数常用来遍历集合
- ForEach()函数接收的参数的类型
/**
* Performs the given [action] on each element.
*/
public inline fun <T> Array<out T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
- ForEach()高阶函数的基本使用
fun main(args: Array<String>) {
val list = listOf(1, 3, 5, 7, 9, 12, 34)
val newlist = ArrayList<Int>()
list.forEach {
val newElement = it * 3 + 2
newlist.add(newElement)
}
println(newlist.toString())
}
Map() 高阶函数常用来对集合做映射的操作
- Map()函数接收的参数类型
/**
* Returns a list containing the results of applying the given [transform] function
* to each element in the original collection.
*/
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
Map和ForEach的区别是Map这个高阶函数是有返回值的
- Map()高阶函数的使用
val newlist = list.map {
it * 3 + 2
}
val newList2 = list.map(Int::toDouble)
println(newlist.toString())
println(newList2.toString())
FlatMap()高阶函数是对集合的集合做遍历的操作
- FlatMap()高阶函数接收的参数类型
/**
* Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
*/
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
- FlatMap()高阶函数的使用
fun main(args: Array<String>) {
val list = listOf(
1..20,
2..5,
100..322
)
val flatlist = list.flatMap { intRange ->
intRange.map { intElement ->
"No.$intElement"
}
}
flatlist.forEach(::println)
}
Reduce()这个高阶函数是用来做累加运算的
- Reduce()高阶函数接收的参数类型
/**
* Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <S, T: S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
- Reduce()高阶函数的使用
fun main(args: Array<String>) {
val list = listOf(
1..20,
2..5,
100..322
)
val flatlist = list.flatMap { it }
// flatlist.forEach(::println)
// println(flatlist.reduce { acc, i -> acc + i })
}
fun factorial(n: Int): Int {
if (n == 0) return 1
return (1..n).reduce { acc, i -> acc * i }
}
Fold()这个高阶函数是用来在一个初始值的基础上做累加运算的,还可以做一些变换
- Fold()高阶函数接收的参数类型
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (acc: R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
- Fold()高阶函数的使用
println( (0..6).map(::factorial).fold(5) { acc, i -> acc + i })
println( (0..6).map(::factorial).fold(StringBuilder()) { acc, i -> acc.append(i).append(",") })
Filter()这个高阶函数是用来做筛选的
- Filter()高阶函数接收的参数类型
/**
* Returns a list containing only elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}