kotlin标准函数

let

let的作用是对一个对象执行let中的操作,并返回指定对象

基本使用

let中的it表示当前对象,return@let表示let的返回值

1
2
3
4
5
val str: String = "Hello"
val strLen: Int = str.let {
return@let it.length
}
println("str length is $strLen")

return@let可以省略,let会自动返回最后一行的表达式,即可写作

1
2
3
val strLen: Int = str.let {
it.length
}

其实本质上还是高阶函数,所以亦可写为完全形式

1
2
3
4
val func: (String) -> Int = fun (it: String): Int {
return it.length
}
val strLen:Int = str.let(func)

安全调用

配合空安全使用,只有在对象不为null时才会执行let中的操作

1
2
3
4
5
6
7
fun main() {
val str: String? = "Hello"
// str不为null时执行let中的操作
str?.let {
println(it)
}
}

链式调用

let的返回值可以作为下一个函数的参数,实现链式调用

1
2
3
4
5
val result: String = str
.let { it.toUpperCase() }
.let { it.trim() }

println(result)

run

扩展函数形式

run的作用是对一个对象执行run中的操作,并返回指定对象,与let的区别在于run中的this表示调用run函数的当前对象

1
2
3
4
5
val str: String = "Hello"
val len:Int = str.run {
// 返回str长度
this.length
}

非扩展函数形式

run的非扩展函数形式是直接调用的,与run的扩展函数的区别在于run中的this代表的是当前类对象

1
2
3
4
val str: String = "Hello"
val len: Int = run {
str.length
}

with

with有两个参数,第一个参数可以是任意对象,第二个参数是一个函数,在第二个参数的函数代码块中,可以使用this代表第一个参数对象,并且返回任意类型的对象

1
2
3
4
5
6
7
8
9
var textView = TextView(context)

textView = with(textView) {
// 在with中,this代表textView
this.text = "hello"
this.textSize = 18f
// 返回textView
return@with this
}

第二个参数的代码块中this可以省略,于是代码可以进一步简化,如下

1
2
3
4
5
6
val textView = with(TextView(context)) {
this.text = "hello"
this.textSize = 18f
this.setTextColor(Color.RED)
return@with this
}

apply

感觉和with差不多,但是apply的返回值是当前对象,而with的返回值是函数的返回值,且with需要传入一个对象,而apply可以直接调用

1
2
3
4
5
val textView = TextView(context).apply {
this.text = "hello"
this.textSize = 18f
this.setTextColor(Color.RED)
}

this同样可以省略

1
2
3
4
5
val textView = TextView(context).apply {
text = "hello"
textSize = 18f
setTextColor(Color.RED)
}

also

感觉和let差不多,但是also的返回值是调用它的对象,而let的返回值是函数参数的返回值;also一般用于执行附加操作

1
2
3
val user = User("小明", 18).also {
println(it)
}