Please help me understand this piece of code in the kotlin docs:-
val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
Now, I understand that first int a = 10000
then in the next line it is comparing it using ===
.
Now the question is why when it assigned boxedA=a
, it checked if it is null using int?
. Can it just be written like this:-
val boxedA: Int=a
Please if I'm understanding it the wrong way, someone guide to check the right place or explain it a bit for me.
First, the
Int
will be mapped to javaint
/Integer
depending on its context. IfInt
is a generic argument, then its mapped type isInteger
. Otherwise, it is a primitive typeint
. for example:Secondly, boxing an
Int
to anInt?
is same behavior as java boxing anint
to anInteger
, for example:This is because Integer only caching values in the range
[-128, 127]
. the the variablea
above is out of the cache range, it will create a new Integer instance for each boxing rather than using a cached value. for example:I have no idea what you mean by this. Making a variable have the type
Int?
makes it a variable that can either store anInt
ornull
. There is no checking happening at this assignment. If you have a non-null value to assign to the variable, just make it non-nullable, without the?
in the type:You can even omit the type, and get
Int
inferred:As for the comparisons:
==
is used for comparing by value in Kotlin (this is the equivalent of usingequals
in Java),===
is used for comparing references (this is==
in Java).When you create
boxedA
andanotherBoxedA
, you create twoInteger
instances under the hood (because nullable variables can't be represented by primitives). These will be equal when compared with==
(they have the same value), but not when compared with===
(they are different instances).You can see the relevant part of the offical docs here.
That is not what it means.
Kotlin's null safety feature does not allow a variable to be set as null by default.
Check here.
This means that
anotherBoxedA
can be assigned null or is nullable.This will be allowed.