日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Kotlin作用域函數(shù)使用示例詳細(xì)介紹_Android

作者:破浪會有時 ? 更新時間: 2023-05-20 編程語言

這里我們將介紹Kotlin 5個作用域函數(shù):let,run,with,apply,also。

1 let

let 可用于范圍界定和空值檢查。在對象上調(diào)用時,let 執(zhí)行給定的代碼塊并返回其最后一個表達(dá)式的結(jié)果。對象可通過引用它(默認(rèn)情況下)或自定義名稱在塊內(nèi)進(jìn)行訪問。

所以,總結(jié)起來,let 有如下三大特征:

// 重點(diǎn)11:使用it替代object對象去訪問其公有的屬性 & 方法
object.let{
   it.todo()
}
// 重點(diǎn)2:判斷object為null的操作
object?.let{//表示object不為null的條件下,才會去執(zhí)行l(wèi)et函數(shù)體
   it.todo()
}
// 重點(diǎn)3:返回值 = 最后一行 / return的表達(dá)式

下面是一些例子(我們可以直接在 Kotlin Playground 中運(yùn)行):

fun customPrint(s: String) {
    print(s.uppercase())
}
fun main() {
    val empty = "test".let {               // Calls the given block on the result on the string "test".
        customPrint(it)                    // 這里的 it 就是 "test",所以 "test" 作為輸入給到 customPrint 函數(shù)中,打印出大寫的 "test"
        it.isEmpty()                       // let 最后返回的是這個,也就是 empty 最終的值是 false
    }
    println(" is empty: $empty")           // 打印結(jié)果 TEST is empty: false。這里的 TEST 是 customPrint 函數(shù) 的打印結(jié)果。注意 print 和 println 的區(qū)別
    fun printNonNull(str: String?) {
        println("Printing \"$str\":")
        str?.let {                         // object不為null的條件下,才會去執(zhí)行l(wèi)et函數(shù)體
            print("\t")
            customPrint(it)
            println()                      // 換行。let最后返回的是這一行
        }
    }
    fun printIfBothNonNull(strOne: String?, strTwo: String?) {
        strOne?.let { firstString ->       
            strTwo?.let { secondString ->
                customPrint("$firstString : $secondString")
                println()
            }
        }
    }
    printNonNull(null)                    // 打印 Printing "null":
    printNonNull("my string")             // 打印 Printing "my string":
	                                      // MY STRING
    printIfBothNonNull("First","Second")  // 打印 FIRST : SECOND
}

從另一個方面,我們來比對一下不使用 let 和使用 let 函數(shù)的區(qū)別。

// 使用kotlin(無使用let函數(shù))
mVar?.function1()
mVar?.function2()
mVar?.function3()
// 使用kotlin(使用let函數(shù))
// 方便了統(tǒng)一判空的處理 & 確定了mVar變量的作用域
mVar?.let {
       it.function1()
       it.function2()
       it.function3()
}

2 run

與 let 函數(shù)類似,run 函數(shù)也返回最后一條語句。另一方面,與 let 不同,運(yùn)行函數(shù)不支持 it 關(guān)鍵字。所以,run 的作用可以是:

  • 調(diào)用同一個對象的多個方法 / 屬性時,可以省去對象名重復(fù),直接調(diào)用方法名 / 屬性即可
  • 定義一個變量在特定作用域內(nèi)
  • 統(tǒng)一做判空處理

下面是一些例子:

fun main() {
    fun getNullableLength(ns: String?) {
        println("for \"$ns\":")
        ns?.run {                                                  // 判空處理
            println("\tis empty? " + isEmpty())                    // 這里我們就發(fā)現(xiàn),在 isEmpty 前不再需要 it
            println("\tlength = $length")                           
            length                                                 // run returns the length of the given String if it's not null.
        }
    }
    getNullableLength(null)   
    // 打印 for "null":
    getNullableLength("")
    // 打印 for "":
    //         is empty? true
    //         length = 0
    getNullableLength("some string with Kotlin")
    // 打印 for "some string with Kotlin":
    //         is empty? false
    //         length = 23
    data class People(val name: String, val age: Int) 
    val people = People("carson", 25)
    people?.run{
      println("my name is $name, I am $age years old")
      // 打印:my name is carson, I am 25 years old
    }
}

3 with

with 是一個非擴(kuò)展函數(shù),可以簡潔地訪問其參數(shù)的成員:我們可以在引用其成員時省略實(shí)例名稱。所以說,run 相當(dāng)于 let 和 with 的集合。

class Configuration(var host: String, var port: Int) 
fun main() {
    val configuration = Configuration(host = "127.0.0.1", port = 9000) 
    with(configuration) {
        println("$host:$port")   // 打印 127.0.0.1:9000
    }
    // instead of:
    println("${configuration.host}:${configuration.port}")    // 打印 127.0.0.1:9000
}

4 apply

apply 對對象執(zhí)行代碼塊并返回對象本身。在塊內(nèi)部,對象由此引用。此函數(shù)對于初始化對象非常方便。所以再重復(fù)一遍,apply函數(shù)返回傳入的對象的本身。

data class Person(var name: String, var age: Int, var about: String) {
    constructor() : this("", 0, "")
}
fun main() {
    val jake = Person()                   
    val stringDescription = jake.apply {  
        // Applies the code block (next 3 lines) to the instance.
        name = "Jake"                                   
        age = 30
        about = "Android developer"
    }.toString()                            
    println(stringDescription)      // 打印 Person(name=Jake, age=30, about=Android developer)
}

5 also

類似 let 函數(shù),但區(qū)別在于返回值:

  • let 函數(shù):返回值 = 最后一行 / return的表達(dá)式
  • also 函數(shù):返回值 = 傳入的對象的本身
// let函數(shù)
var result = mVar.let {
               it.function1()
               it.function2()
               it.function3()
               999
}
// 最終結(jié)果 = 返回999給變量result
// also函數(shù)
var result = mVar.also {
               it.function1()
               it.function2()
               it.function3()
               999
}
// 最終結(jié)果 = 返回一個mVar對象給變量result

另一個類似的例子:

data class Person(var name: String, var age: Int, var about: String) {
             constructor() : this("", 0, "")
}
fun writeCreationLog(p: Person) {
    println("A new person ${p.name} was created.")              
}
fun main() {
    val jake = Person("Jake", 30, "Android developer")   // 1
        .also {                                          // 2 
            writeCreationLog(it)                         // 3
        }
    println(jake)   
    // 最終打印:
    // A new person Jake was created.
    // Person(name=Jake, age=30, about=Android developer)
}

原文鏈接:https://blog.csdn.net/zyctimes/article/details/127814513

欄目分類
最近更新