定义:
inline fun run(block: () -> R): R //1
Calls the specified function block and returns its result.
inline fun T.run(block: T.() -> R): R //2
Calls the specified function block with this value as its receiver and returns its result.
第一种使用:直接使用run函数返回其结果(最后一行的结果)
fun runTest() {
val a = run {
"abc"
1
}
val b = run {
1
2
"abc"
}
println(a)
println(b)
}
打印结果:
1
abc
第二种使用:调用某个对象(该对象作为接收者)的run函数并返回结果
fun runTestWithT() {
val a = 1.run {
"$this 和 abc"
}
println(a)
}
打印结果:
1 和 abc
定义:
inline fun T.let(block: (T) -> R): R
Calls the specified function block with this value as its argument and returns its result.
使用:调用某个对象(该对象作为函数的参数)的let的函数并返回结果
fun letTest() {
val let = "abc".let {
println(it)
1
}
println(let)
}
打印结果:
abc
1
定义 :
inline fun T.also(block: (T) -> Unit): T
Calls the specified function block with this value as its argument and returns this value.
使用: 调用某一对象的also 函数(该对象作为函数参数)并返回改对象
fun alsoTest() {
val also = "abc".also {
println(it)
}
println(also)
}
打印结果:
abc
abc
定义:
inline fun T.apply(block: T.() -> Unit): T
Calls the specified function block with this value as its receiver and returns this value.
使用:调用对象(该对象作为接收者)的apply函数并返回该对象
fun applyTest(){
val apply ="abc".apply {
println(this)
}
println(apply)
}
打印结果:
abc
abc
定义:
inline fun with(receiver: T, block: T.() -> R): R
Calls the specified function block with the given receiver as its receiver and returns its result.
使用:使用给定接收器作为接收器调用with函数并返回其结果
fun withTest() {
val with = with("abc") {
println(this)
1111
}
println(with)
}
打印结果:
abc
1111
with 函数的使用形式与其他几个函数的类型不一样
with 函数重要的一个作用是使用它实现构建者模式:
举个例子:
class Student(builder: Builder) {
var name: String = ""
var age = 1
init {
name = builder.name
age = builder.age
}
class Builder {
var name: String = ""
var age: Int = 0
fun builder(): Student = Student(this)
}
}
使用with函数构建:
fun withTest() {
val student = with(Student.Builder()) {
this.age = 18
this.name = "marry"
builder()
}
println("name: ${student.name},age:${student.age}")
}
打印结果:
name: marry,age:18
看了上面的几个简单的使用,我们可能就能从几个函数的定义可以看出他们区别:
返回其他结果 :run ,let,with
返回自身结果 :also ,apply
调用者作为参数 :let,also
调用者作为接收者:run,with,apply
参考:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/index.html