Swift 的 if Let 語句在 Kotlin 中的等效
Swift if let 語句允許將 if 和 null 檢查語句組合到單個程式碼塊中。它通過檢查變數或常量的值是否為空來幫助消除所有 -nil 指標異常錯誤。
如果我們想在 Kotlin 中使用同樣的東西怎麼辦?在 Kotlin 中,我們可以使用 let 和 run 或 Elvis 運算子 (? :) 等價於 Swift if let 語句。
本文將演示 let 和 run 函式作為 Kotlin 中等效的 Swift if let 語句。
比較 Swift if let 語句和 Kotlin let 和 run 函式
這是我們如何使用 Swift if let 語句的方法。
if let x = y.val {
} else {
}
let 和 run 函式的語法:
val x = y?.let {
// enter if y is not null.
} ?: run {
// enter if y is null.
}
在上面的語法中,只有在 Elvis 運算子之後有多行程式碼時,我們才需要使用 run 程式碼塊。如果 Elvis 運算子後只有一行程式碼,我們可以跳過 run 塊。
此外,當使用 Kotlin let 和 run 時,編譯器無法從 let 和 run 塊中訪問變數。由於 Kotlin Elvis 操作符是一個 nil-checker,run 程式碼只會在 y 為 null 或 let 塊的計算結果為 null 時執行。
將 let 和 run 函式用作 Kotlin 中等效的 Swift if let 語句
讓我們看一個例子來了解如何在程式中實現 Kotlin let 和 run 函式。此示例將檢查變數的值。
如果 let 塊為空,編譯器將執行它;否則,它將執行 run 塊。
示例 1:
fun main(args: Array<String>) {
val y="Hello"
val x = y?.let {
// This code runs if y is not null
println("Code A");
} ?: run {
// This code runs if y is null
println("Code B");
}
}
輸出:

輸出執行 let 程式碼,因為 y 的值不為空。
現在,讓我們嘗試將 y 的值設為 null。
示例 2:
fun main(args: Array<String>) {
val y= null
val x = y?.let {
// This code runs if y is not null
println("Code A");
} ?: run {
// This code runs if y is null
println("Code B");
}
}
輸出:

Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.
LinkedIn