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?
Nullable and Non-Nullable Types in Kotlin – Kotlin type system has distinguish two types of references that can hold null (nullable references) and those that can not (non-null references). A variable of type String can not hold null. If we try to assign null to the variable, it gives compiler error.
Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.
Kotlin's type system is aimed at eliminating the danger of null references, also known as The Billion Dollar Mistake. One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception.
Alternatively, you can use the isEmpty() function to check for an empty string in Kotlin. To check for null as well, it should be preceded by a null check. To check for the opposite, i.e., the string is not empty, use the isNotEmpty() function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With