下面的代码不会编译,因为变量myType
可以为null.有没有办法在Kotlin中为可空类型执行with
块?
val myType: MyType? = null
with(myType) {
aMethodThatBelongsToMyType()
anotherMemberMethod()
}
下面的代码不会编译,因为变量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()
}
}