我试图找出如何在kotlin中实现"if let + cast"的组合:
在swift中:
if let user = getUser() as? User {
// user is not nil and is an instance of User
}
Run Code Online (Sandbox Code Playgroud)
我看到了一些文档,但他们对此组合没有任何说明
https://medium.com/@adinugroho/unwrapping-sort-of-optional-variable-in-kotlin-9bfb640dc709 https://kotlinlang.org/docs/reference/null-safety.html
Ale*_*lov 28
(getUser() as? User)?.let { user ->
...
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是在传递给lambda的lambda中使用智能强制转换let:
getUser().let { user ->
if (user is User) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
但也许最可读的只是引入变量并在那里使用智能转换:
val user = getUser()
if (user is User) {
...
}
Run Code Online (Sandbox Code Playgroud)
Kotlin可以根据常规if语句自动确定一个值是否为nil(在当前范围内),而无需特殊语法。
val user = getUser()
if (user != null) {
// user is known to the compiler here to be non-null
}
Run Code Online (Sandbox Code Playgroud)
它也相反
val user = getUser()
if (user == null) {
return
}
// in this scope, the compiler knows that user is not-null
// so there's no need for any extra checks
user.something
Run Code Online (Sandbox Code Playgroud)
小智 5
在Kotlin你可以使用let:
val user = getUser()?.let { it as? User } ?: return
Run Code Online (Sandbox Code Playgroud)
该解决方案最接近防护,但它可能是有用的.
| 归档时间: |
|
| 查看次数: |
5649 次 |
| 最近记录: |