fun main() {
val set: Set<Int>?
set = null
val emptySet: Set<Int> = set.orEmpty()
}
Run Code Online (Sandbox Code Playgroud)
即使将 set 变量显式键入为 Set <Int>,仍无法弄清楚为什么?编译器认为扩展方法set.orEmpty () set - 是一个字符串,因此会崩溃并出现错误:
Kotlin:类型不匹配:推断类型为 String,但预期为 Set
但是当在一行中声明和初始化时,一切都会正确发生:
fun main() {
val set: Set<Int>? = null
val emptySet: Set<Int> = set.orEmpty()
}
Run Code Online (Sandbox Code Playgroud)