日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Kotlin 标准库中run、let、also、apply、with函数的用法和区别

發布時間:2025/4/5 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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復制代碼

看了上面的幾個簡單的使用,我們可能就能從幾個函數的定義可以看出他們區別:

從返回結果不同來看

  • 返回其他結果runletwith

  • 返回自身結果alsoapply

從對象調用的作用來看

  • 調用者作為參數letalso

  • 調用者作為接受者runwithapply

參考:kotlinlang.org/api/latest/…

轉載于:https://juejin.im/post/5c3eb235f265da61587761c5

總結

以上是生活随笔為你收集整理的Kotlin 标准库中run、let、also、apply、with函数的用法和区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。