科特林 – 等效于斯威夫特的“如果让+投”

我试图找出如何在kotlin中实现“if let + cast”的组合:

在迅速:

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

一种选择是使用安全的投射操作员 + 安全呼叫 + let

 (getUser() as? User)?.let { user -> ... } 

另一种方法是在传递给lambda的lambda中使用一个smart cast :

 getUser().let { user -> if (user is User) { ... } } 

但也许最可读的是只引入一个variables,并在那里使用一个聪明的演员:

 val user = getUser() if (user is User) { ... } 

在Kotlin中,你可以使用let:

 val user = getUser()?.let { it as? User } ?: return 

这个解决方案是最接近守卫,但它可能是有用的。

Kotlin可以基于常规的if语句自动判断当前范围中的值是否为零,而不需要特殊的语法。

 val user = getUser() if (user != null) { // user is known to the compiler here to be non-null } 

它也是相反的

 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 

在Kotlin你可以使用:

 (getUser() as? User)?.let { user -> // user is not null and is an instance of User } 

as? 是一个“安全的”转换运算符 ,返回null而不是在失败时抛出错误。

这个如何?

 val user = getUser() ?: return