Kotlin 标准库中run、let、also、apply、with函数的用法和区别
生活随笔
收集整理的這篇文章主要介紹了
Kotlin 标准库中run、let、also、apply、with函数的用法和区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
run 函數
定義:
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函數返回其結果(最后一行的結果)
fun runTest() {val a = run {"abc"1}val b = run {12"abc"}println(a)println(b) } 復制代碼打印結果:
1abc復制代碼第二種使用:調用某個對象(該對象作為接收者)的run函數并返回結果
fun runTestWithT() {val a = 1.run {"$this 和 abc"}println(a) } 復制代碼打印結果:
1 和 abc 復制代碼let 函數
定義:
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.復制代碼使用:調用某個對象(該對象作為函數的參數)的let的函數并返回結果
fun letTest() {val let = "abc".let {println(it)1}println(let) } 復制代碼打印結果:
abc1復制代碼also 函數
定義 :
inline fun <T> 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 復制代碼apply 函數
定義:
inline fun <T> 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) } 復制代碼打印結果:
abcabc復制代碼with 函數
定義:
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.復制代碼使用:使用給定接收器作為接收器調用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 = 1init {name = builder.nameage = builder.age}class Builder {var name: String = ""var age: Int = 0fun builder(): Student = Student(this)} } 復制代碼使用with函數構建:
fun withTest() {val student = with(Student.Builder()) {this.age = 18this.name = "marry"builder()}println("name: ${student.name},age:${student.age}") } 復制代碼打印結果:
name: marry,age:18復制代碼看了上面的幾個簡單的使用,我們可能就能從幾個函數的定義可以看出他們區別:
從返回結果不同來看
-
返回其他結果 :run ,let,with
-
返回自身結果 :also ,apply
從對象調用的作用來看
-
調用者作為參數 :let,also
-
調用者作為接受者:run,with,apply
參考:kotlinlang.org/api/latest/…
轉載于:https://juejin.im/post/5c3eb235f265da61587761c5
總結
以上是生活随笔為你收集整理的Kotlin 标准库中run、let、also、apply、with函数的用法和区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring cloud java b2
- 下一篇: MongoDB-数据类型