如何对可空类型使用 Kotlin 的“with”表达式

How to use Kotlin's `with` expression for nullable types

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

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

您可以将可空类型转换为具有后缀 !! 的非可空类型:

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

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

更好的方法是通过进行空安全调用并使用 apply 扩展函数而不是 [=16,使代码块的执行依赖于非空值=]:

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

另一种选择是使用 if 语句检查该值是否为非空值。编译器将在 if 块中插入一个到非空类型的智能转换:

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

您可以定义自己的 with 函数来接受可为 null 的值,然后根据对象是否为 null 来确定是否实际 运行。

像这样:

fun <T, R> with(receiver: T?, block: T.() -> R): R? {
    return if(receiver == null) null else receiver.block()
}

然后您可以在示例中按照您想要的方式调用代码,没有任何问题,如果您传入的是 null.

,结果将等于 null

或者,如果代码块应该(并且可能)是 运行,即使 myTypenull,那么您应该这样定义它:

fun <T, R> with(receiver: T?, block: T?.() -> R): R {
    return receiver.block()
}