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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)