小编Jlu*_*uoH的帖子

在空对象上调用扩展方法时,会在错误的类型上调用

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)

extension-methods kotlin

9
推荐指数
1
解决办法
249
查看次数

标签 统计

extension-methods ×1

kotlin ×1