如何使用Kotlin的“with`表达式为可空类型

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

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

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

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

如果值确实为null,则会抛出NullPointerException ,所以通常应该避免这种情况。

更好的方法是通过进行一个空安全的调用,并使用apply扩展函数而不是使用下面的代码来使代码块的执行取决于非空的值:

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

还有一个选择是用if语句检查值是否为非空值。 编译器会在if块中插入一个智能转换为不可空的类型:

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

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

喜欢这个:

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