Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
Morozov Avatar asked Nov 07 '17 16:11

Morozov


People also ask

What type is null in Kotlin?

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.

How does Kotlin handle null values?

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.

Why do we use null in Kotlin?

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.

Is empty string null in Kotlin?

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.


1 Answers

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 
like image 103
BakaWaii Avatar answered Oct 16 '22 23:10

BakaWaii