Kotlin 标准库中run、let、also、apply、with函数的用法和区别
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.復(fù)制代碼第一種使用:直接使用run函數(shù)返回其結(jié)果(最后一行的結(jié)果)
fun runTest() {val a = run {"abc"1}val b = run {12"abc"}println(a)println(b) } 復(fù)制代碼打印結(jié)果:
1abc復(fù)制代碼第二種使用:調(diào)用某個對象(該對象作為接收者)的run函數(shù)并返回結(jié)果
fun runTestWithT() {val a = 1.run {"$this 和 abc"}println(a) } 復(fù)制代碼打印結(jié)果:
1 和 abc 復(fù)制代碼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.復(fù)制代碼使用:調(diào)用某個對象(該對象作為函數(shù)的參數(shù))的let的函數(shù)并返回結(jié)果
fun letTest() {val let = "abc".let {println(it)1}println(let) } 復(fù)制代碼打印結(jié)果:
abc1復(fù)制代碼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.復(fù)制代碼使用: 調(diào)用某一對象的also 函數(shù)(該對象作為函數(shù)參數(shù))并返回改對象
fun alsoTest() {val also = "abc".also {println(it)}println(also) } 復(fù)制代碼打印結(jié)果:
abc abc 復(fù)制代碼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.復(fù)制代碼使用:調(diào)用對象(該對象作為接收者)的apply函數(shù)并返回該對象
fun applyTest(){val apply ="abc".apply {println(this)}println(apply) } 復(fù)制代碼打印結(jié)果:
abcabc復(fù)制代碼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.復(fù)制代碼使用:使用給定接收器作為接收器調(diào)用with函數(shù)并返回其結(jié)果
fun withTest() {val with = with("abc") {println(this)1111}println(with) } 復(fù)制代碼打印結(jié)果:
abc 1111 復(fù)制代碼with 函數(shù)的使用形式與其他幾個函數(shù)的類型不一樣
with 函數(shù)重要的一個作用是使用它實(shí)現(xiàn)構(gòu)建者模式:
舉個例子:
class Student(builder: Builder) {var name: String = ""var age = 1init {name = builder.nameage = builder.age}class Builder {var name: String = ""var age: Int = 0fun builder(): Student = Student(this)} } 復(fù)制代碼使用with函數(shù)構(gòu)建:
fun withTest() {val student = with(Student.Builder()) {this.age = 18this.name = "marry"builder()}println("name: ${student.name},age:${student.age}") } 復(fù)制代碼打印結(jié)果:
name: marry,age:18復(fù)制代碼看了上面的幾個簡單的使用,我們可能就能從幾個函數(shù)的定義可以看出他們區(qū)別:
從返回結(jié)果不同來看
-
返回其他結(jié)果 :run ,let,with
-
返回自身結(jié)果 :also ,apply
從對象調(diào)用的作用來看
-
調(diào)用者作為參數(shù) :let,also
-
調(diào)用者作為接受者:run,with,apply
參考:kotlinlang.org/api/latest/…
轉(zhuǎn)載于:https://juejin.im/post/5c3eb235f265da61587761c5
總結(jié)
以上是生活随笔為你收集整理的Kotlin 标准库中run、let、also、apply、with函数的用法和区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring cloud java b2
- 下一篇: Spring:容器