let函数会将参数传入到lambda作用域中,返回作用域的最后一行

1
2
3
4
val res = listOf(1,2,3).first().let {
it * it
}
println(res)

also函数会返回接收者对象,作用域和功能类似,传入参数

1
2
3
4
5
6
7
8
val s = "hello"
var m = ""
s.also {
println(it)
}.also {
m = it.uppercase()
}
println(m)

apply函数会返回接受者对象并执行lambda中的内容,作用域中不需要再写当前参数

1
2
3
4
val s = "hello".apply {
capitalize()
}
println(s)

run函数和apply作用域一样,但是返回lambda的结果,此外run还可以用来执行函数(链式调用也可以)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fun main(){

val res = "hello".run {
length
}
println(res)

"The people of china"
.run(::isTooLong)
.run(::showMessage)
}


fun isTooLong(name : String) = name.length >= 10

fun showMessage(isLong: Boolean) :String{
return if (isLong){
println("name is too long")
"name is too long"
}else{
println("Please rename")
"Please rename"
}
}

with函数功能和run一样,但是需要将值参作为第一个参数传入

1
2
3
4
5
6
7
fun main(){

val isTooLong = with("The people of China"){
length > 10
}
println(isTooLong)
}

takeIf函数的lambda作用域和let相似,此函数需要在lambda作用域中给出true或者false ,true返回当前的对象,false返回Null

takeUnless对于lambda的结果处理与之相反

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fun main() {

var isLong = "The people of China"
.takeIf { it.length >= 10 }
?.length
println(isLong)

//等价于上面
val str = "The people of China"
isLong = if (str.length >= 10) {
str.length
} else {
null
}
println(isLong)

isLong = str
.takeUnless { it.length <= 10 }
?.length
println(isLong)
}

本文地址: http://www.yppcat.top/2021/12/08/kotlin笔记-标准函数/