string - 为什么 Kotlin 中 null + null 的类型是隐式 String?

以下 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/

相关文章:

android - 从 Activity Kotlin 中获取额外的字符串

kotlin - 从 lambdas 或 Kotlin : 'return' is not allo

android - 使用 Kotlin 关闭/隐藏 Android 软键盘

android - 使用 Kotlin 组合整数标志的最佳方法?

kotlin - 如何在 Kotlin 中定义非序数枚举?

kotlin - 如何在一行上声明多个属性

kotlin - 做任何==对象

kotlin - 从 Kotlin 中的密封类扩展数据类

android - 使用 Retrofit 方法更具表现力

android - Kotlin 错误 : Dagger does not support inje