日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/4/5 58 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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函数的用法和区别的全部內容,希望文章能夠幫你解決所遇到的問題。

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