run 函數(shù)
定義:
inline fun <R> run(block: () -> R): R //1
Calls the specified function block and returns its result.
inline fun <T, R> T.run(block: T.() -> R): R //2
Calls the specified function block with this value as its receiver and returns its result.
第一種使用:直接使用run函數(shù)返回其結(jié)果(最后一行的結(jié)果)
fun runTest() {
val a = run {
"abc"
1
}
val b = run {
1
2
"abc"
}
println(a)
println(b)
}
打印結(jié)果:
1
abc
第二種使用:調(diào)用某個(gè)對(duì)象(該對(duì)象作為接收者)的run函數(shù)并返回結(jié)果
fun runTestWithT() {
val a = 1.run {
"$this 和 abc"
}
println(a)
}
打印結(jié)果:
1 和 abc
let 函數(shù)
定義:
inline fun <T, R> T.let(block: (T) -> R): R
Calls the specified function block with this value as its argument and returns its result.
使用:調(diào)用某個(gè)對(duì)象(該對(duì)象作為函數(shù)的參數(shù))的let的函數(shù)并返回結(jié)果
fun letTest() {
val let = "abc".let {
println(it)
1
}
println(let)
}
打印結(jié)果:
abc
1
also 函數(shù)
定義 :
inline fun <T> T.also(block: (T) -> Unit): T
Calls the specified function block with this value as its argument and returns this value.
使用: 調(diào)用某一對(duì)象的also 函數(shù)(該對(duì)象作為函數(shù)參數(shù))并返回改對(duì)象
fun alsoTest() {
val also = "abc".also {
println(it)
}
println(also)
}
打印結(jié)果:
abc
abc
apply 函數(shù)
定義:
inline fun <T> T.apply(block: T.() -> Unit): T
Calls the specified function block with this value as its receiver and returns this value.
使用:調(diào)用對(duì)象(該對(duì)象作為接收者)的apply函數(shù)并返回該對(duì)象
fun applyTest(){
val apply ="abc".apply {
println(this)
}
println(apply)
}
打印結(jié)果:
abc
abc
with 函數(shù)
定義:
inline fun <T, R> with(receiver: T, block: T.() -> R): R
Calls the specified function block with the given receiver as its receiver and returns its result.
使用:使用給定接收器作為接收器調(diào)用with函數(shù)并返回其結(jié)果
fun withTest() {
val with = with("abc") {
println(this)
1111
}
println(with)
}
打印結(jié)果:
abc
1111
with 函數(shù)的使用形式與其他幾個(gè)函數(shù)的類型不一樣
with 函數(shù)重要的一個(gè)作用是使用它實(shí)現(xiàn)構(gòu)建者模式:
舉個(gè)例子:
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函數(shù)構(gòu)建:
fun withTest() {
val student = with(Student.Builder()) {
this.age = 18
this.name = "marry"
builder()
}
println("name: ${student.name},age:${student.age}")
}
打印結(jié)果:
name: marry,age:18
看了上面的幾個(gè)簡單的使用,我們可能就能從幾個(gè)函數(shù)的定義可以看出他們區(qū)別:
從返回結(jié)果不同來看
返回其他結(jié)果 :run 析二,let粉洼,with
返回自身結(jié)果 :also ,apply
從對(duì)象調(diào)用的作用來看
調(diào)用者作為參數(shù) :let叶摄,also
調(diào)用者作為接收者:run属韧,with,apply
參考:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/index.html