以下是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".

However, I don't understand why this happens - is it due to some special feature of the language?

推荐答案

Probably because String?.plus(Any?) is the only plus function which accepts a nullable type as a receiver in Kotlin library. Therefore, when you call null + null, the compiler will treat the first null as String?.

If you define an extension function where the receiver type is Int? and the return type is Int, then x will be inferred as Int.

public operator fun Int?.plus(other: Any?): Int = 1
val x = null + null

If you declare another similar function within the same file (nullable type as the receiver type), when you call null + null, it causes the compile time error: Overload resolution ambiguity. All these functions match..

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

Kotlin相关问答推荐

数据源配置

合并状态流

Kotlin 说不需要强制转换,但删除后会出现新警告

找不到有效的 Docker 环境

使用调度程序运行异步 Kotlin 代码

在kotlin中匹配多个变量

Kotlin中用于调用常量名称的枚举类方法之间的区别

Kotlin 可空泛型

Kotlin:使用另一个列表和字母顺序对列表进行排序的有效方法

gradle 如何 Select 以-jvm结尾的库?

AIDL 中的 Parcelize 注释:Incompatible types: Object cannot be converted to MyCustomObject

如何使 TextInputEditText 只读?

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

在 Scaffold Jetpack Compose 内的特定屏幕上隐藏顶部和底部导航器

TextField maxLength - Android Jetpack Compose

如何通过反射使用 Kotlin 对象

哪里可以找到aapt2日志(log)?

参数不匹配;SimpleXML

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

Android Compose 生产准备好了吗?