首页 文章

Kotlin - 等同于Swift的“if let cast”的组合

提问于
浏览
16

我试图找出如何在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 回答

  • 4

    Kotlin可以根据不需要特殊语法的常规if语句自动判断当前作用域中的值是否为nil .

    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
    
  • 1

    在Kotlin你可以使用:

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

    as?'safe' cast operator,返回 null 而不是在失败时抛出错误 .

  • 0

    这个如何?

    val user = getUser() ?: return
    
  • 18

    一种选择是使用safe cast operator safe call let

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

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

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

    但也许最可读的只是引入变量并在那里使用智能转换:

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

    在Kotlin你可以使用let:

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

    该解决方案最接近防护,但它可能是有用的 .

相关问题