gpt4 book ai didi

kotlin - 如何将 Kotlin 的 `with` 表达式用于可空类型

转载 作者:IT老高 更新时间:2023-10-28 13:34:45 26 4
gpt4 key购买 nike

下面的代码将无法编译,因为变量 myType 可以为 null。有没有办法在 Kotlin 中为可空类型执行 with block ?

    val myType: MyType? = null
with(myType) {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}

最佳答案

您可以使用后缀 !! 将可空类型转换为不可空类型:

with(myType!!) {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}

如果该值确实为null,它会抛出一个NullPointerException,所以一般应该避免这种情况。

一个更好的方法是通过进行空安全调用并使用 apply 扩展函数而不是 :

myType?.apply {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}

另一个选项是使用 if 语句检查值是否非空。编译器会在 if block 内插入一个智能转换为一个不可为空的类型:

if (myType != null) {
with(myType) {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}
}

关于kotlin - 如何将 Kotlin 的 `with` 表达式用于可空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35723226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com