我试图找出如何在kotlin中实现“if let cast”的组合:
在swift中:
if let user = getUser() as? User {
// user is not nil and is an instance of User
}
我看到了一些文档,但他们对此组合没有任何说明
https://medium.com/@adinugroho/unwrapping-sort-of-optional-variable-in-kotlin-9bfb640dc709 https://kotlinlang.org/docs/reference/null-safety.html
5 回答
Kotlin可以根据不需要特殊语法的常规if语句自动判断当前作用域中的值是否为nil .
它反过来也是相反的
在Kotlin你可以使用:
as?
是'safe' cast operator,返回null
而不是在失败时抛出错误 .这个如何?
一种选择是使用safe cast operator safe call let:
另一种方法是在传递给
let
的lambda中使用smart cast:但也许最可读的只是引入变量并在那里使用智能转换:
在Kotlin你可以使用let:
该解决方案最接近防护,但它可能是有用的 .