是否可以使以下代码在Kotlin中进行编译?
val variable: String? = "string"
val (a, b) = variable?.run {
1 to 2
}
编译器不允许解构,因为右侧的表达式键入为可为空的Pair<Int, Int>?
,并且不清楚a
为空时b
和variable
应该保留什么。
要解决这个问题,您需要在=
之后获得一个非空的表达式。
有很多不同的方法来处理可为空的值并从可为空的值中产生非空值,请参见:In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them
例如,如果要提供a
和b
的后备值,则按如下所示使用?:
运算符:
val (a, b) = variable?.run {
1 to 2
} ?: (0 to 0)
例如,替代方法是先检查variable
是否为空:
val (a, b) = checkNotNull(variable) { "variable should never be null" }.run {
1 to 2
}
Null没有任何破坏性声明。如果您希望像一个一对空值一样将空值解构,则可以添加以下扩展名:
operator fun <T> Pair<T, *>?.component1() = this?.component1()
operator fun <T> Pair<*, T>?.component2() = this?.component2()
否则,如其他答案所示,您需要使用Elvis运算符提供默认值。
这不是自动的,因为它不知道您想要什么。根据您的操作,0 to 0
可能是最合适的,或者-1 to -1
或0 to null
或null to null
。