網(wǎng)站首頁 編程語言 正文
這里我們將介紹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
相關(guān)推薦
- 2022-12-04 Dart?異步編程生成器及自定義類型用法詳解_Dart
- 2022-07-27 python語法學(xué)習(xí)之super(),繼承與派生_python
- 2022-06-28 .Net連接數(shù)據(jù)庫的方式詳解_實(shí)用技巧
- 2022-11-03 Python列表推導(dǎo)式,元組推導(dǎo)式,字典推導(dǎo)式,集合推導(dǎo)式_python
- 2023-07-18 A component required a bean of type ‘xxx‘ that cou
- 2022-03-27 C++函數(shù)重載介紹與原理詳解_C 語言
- 2023-01-28 Python多進(jìn)程并發(fā)與同步機(jī)制超詳細(xì)講解_python
- 2022-05-03 python讀寫xml文件實(shí)例詳解嘛_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支