科特林 – 等效于斯威夫特的“如果让+投”
我试图找出如何在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
- 信号7(SIGBUS),代码2(BUS_ADRERR)
- 如何从Kotlin函数types返回
- Kotlingenericstypes,types推断失败
- Gradle sinc以kotlin扩展失败。 输入字符串:“”在build.gradle文件模块(应用程序)
- Android / Kotlin使用Java.io.File读取文件:路径有问题
- java.lang.RuntimeException:java.lang.RuntimeException:com.android.builder.dexing.DexArchiveMergerException:无法合并dex
- 使用kotlin编译android项目时出错
- 不能用Dagger2提供合格的字符串
- 在另一个模块的function模块中找不到Kotlin类