以下 Kotlin 代码:
val x = null + null
导致 x
的类型为 String
,根据 String.plus
的文档,这是正确的:
Concatenates this string with the string representation of the given [other] object. If either the receiver or the [other] object are null, they are represented as the string "null".
但是,我不明白为什么会发生这种情况 - 是因为该语言的某些特殊功能吗?
最佳答案
可能是因为 String?.plus(Any?)
是 Kotlin 库中唯一接受可空类型作为接收器的 plus
函数。因此,当你调用null + null
时,编译器会将第一个null
当作String?
。
如果你定义一个扩展函数,接收器类型是Int?
,返回类型是Int
,那么x
会被推断为整数
.
public operator fun Int?.plus(other: Any?): Int = 1
val x = null + null
如果在同一个文件中声明另一个类似的函数(可以为null的类型作为receiver类型),当你调用null + null
时,会导致编译时错误:Overload resolution ambiguity。所有这些函数都匹配。
.
public operator fun Int?.plus(other: Any?): Int = 1
public operator fun Float?.plus(other: Any?): Float = 1F
val x = null + null //compile time error
https://stackoverflow.com/questions/47162946/