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