Search code examples
stringkotlinnullable

Why is the type of null + null implicitly String in Kotlin?


The following Kotlin code:

val x = null + null

results in x being of type String, which is correct as according to the docs for 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?


Solution

  • 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