> 文章列表 > kotlin的一些标准函数

kotlin的一些标准函数

kotlin的一些标准函数

文章目录

      • 1. this 上下文
        • with
        • run
        • apply
      • 2. it 上下文
        • let
        • also
      • 3. 其他好用的函数
        • map
        • filter
        • reduce
        • flatMap

kotlin的标准函数有 run,let,with 等等,平时用的时候没有太在意他们之间的差异,现在来总结对比一下。
将他们分成 this 上下文和 it 上下文两类。

1. this 上下文

包括 with,run,apply 这三个函数。

with

最后一行代码作为返回值

val list = mutableListOf("Apple", "Tree")
with(list) {add("Hello")add("World")
}
Log.i(TAG, list.toString())

输出:[Apple, Tree, Hello, World]

run

最后一行代码作为返回值,功能和 with 一样,只不过调用方式有差异。

val list = mutableListOf("Apple", "Tree")
list.run {add("Hello")add("World")
}
Log.i(TAG, list.toString())

输出:[Apple, Tree, Hello, World]

apply

返回自己

val list = mutableListOf("Apple", "Tree")
val test = list.apply {add("Hello")add("World")
}

2. it 上下文

包括 let,also

let

最后一行代码作为返回值,通常和 ?一起使用,用于判空

val list = mutableListOf("Apple", "Tree")
list.let {it.add("Hello")it.add("World")
}

also

返回自己,和 apply 标准函数一样返回自己,只不过 apply 提供的是 this 上下文

val list = mutableListOf("Apple", "Tree")
var test = list.also {it.add("Hello")it.add("World")
}

3. 其他好用的函数

平时比较常用到的有 map,reduce,filter,flatMap 等。

map

map 可以将一个集合映射成另外一个集合

val list = mutableListOf("Apple", "Tree")
val num = list.map { it -> it.length }
Log.i(TAG,num.toString())

输出:[5, 4]

filter

filter 顾名思义可以帮助我们从集合中挑选出符合要求的元素

val list = mutableListOf("Apple", "Tree")
val filter = list.filter {  it.length > 4 }
Log.i(TAG,filter.toString())

输出:[“Apple”]

reduce

reduce 可以累积一个操作

val list = mutableListOf("Apple", "Tree")
val reduceStr = list.reduce { acc, s -> acc+"$"+s }
Log.i(TAG,"reduceStr:${reduceStr}")

输出:Apple$Tree

flatMap

flatMap 可以将嵌套的 list 抚平

val nestList = listOf(listOf(1,2,3), listOf(4,5,6), listOf(7,8,9)
)
val flatList = nestList.flatMap { it }
Log.i(TAG,flatList.toString())

输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]