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

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

推荐答案

You can convert a nullable type to a non-nullable type with the suffix !!:

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

If the value is indeed null, it will throw a NullPointerException, so this should generally be avoided.

一种更好的方法是通过执行NULL-SAFE调用并使用apply扩展函数而不是with来使代码挡路的执行依赖于值非NULL:

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

Yet another option is to check if the value is non-null with an if statement. The compiler will insert a smart cast to a non-nullable type inside the if-block:

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

Kotlin相关问答推荐

创建具有共同父类型的两种不同类型对象的列表的最有效方法是什么?

计算值的Elvis算子

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

在Webflux应用程序中通过kotlin协程启动fire and forget job

如何检测一个值是否是Kotlin中的枚举实例?

在 Kotlin 中定义基于多态函数的泛型函数

为什么Kotlin有次构造函数和init块?

如何在 Kotlin 中初始化 Short 数组?

判断 Kotlin 变量是否为函数

Lets plot Kotlin中的多轴比例

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

带有迭代器函数的 Kotlin 无限序列

在java代码中使用kotlin库

kotlin RecyclerView分页

Kotlin的BiMap/2-way hashmap

IllegalStateException:function = , count = 3, index = 3

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

将字符串转换为HashMap的最简单方法

kotlin中密封类和密封接口的区别是什么

Kotlin Realm:如果类包含自定义构造函数,则必须声明一个不带参数的公共构造函数