Kotlin boxed Int is not the same
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
and then the next line compares it with ===
.
Now the question is why, when it assigned boxedA=a
, it was checking if it was null using int?
. Can it just be written like this: -
val boxedA: Int=a
Please if I am getting this wrong, someone can help check the correct place or explain it a bit for me.
source to share
when he assigned
boxedA = a
it was checking if it was null usingint?
I have no idea what you mean by that. When a variable is created, the type int?
makes it a variable, which can either store Int
or null
. No validation occurs in this job. If you have a non-null value to assign to a variable, just make it non-empty, without ?
in the type:
val copyOfA: Int = a
You can even omit the type and get the Int
output:
val copyOfA = a
As for comparisons:
==
used for comparison by value in Kotlin (this is equivalent to use equals
in Java), ===
used for comparison of references (this is ==
in Java).
On creation boxedA
and anotherBoxedA
you create two instances Integer
under the hood (since null-valued variables cannot be represented by primitives). They will be equal compared to ==
(they have the same meaning), but not compared to ===
(they are different instances).
You can see the relevant part of the official docs here .
source to share
did he check if it is null using int?
This is not what it means.
Kotlin's null security feature does not allow a default variable to be set.
Check it here .
val anotherBoxedA: Int? = a
This means it anotherBoxedA
can be assigned null or equal to NULL.
val anotherBoxedA: Int? = null
This will be allowed.
source to share
First, it Int
will render in java Int
/ Integer
depending on its context. If Int
is a generic argument, then its display type Integer
. Otherwise, it is a primitive type Int
. eg:
val a:Int = 1
//final int a = 1; //mapped to java code
val numbers:List<Int> = asList(1,2,3)
//final List<Integer> numbers = asList(1, 2, 3); //mapped to java code
Second, boxing Int
on Int?
the same behavior as java boxing Int
on Integer
, for example:
val a:Int = 1 // int a = 1;
val b:Int? = a; // Integer b = a;
Why are the nested integers not the same?
This is because Integer only cache values ββin a range [-128, 127]
. the above variable a
is out of the cache scope, it will create a new Integer instance for each box , not using the cached value. eg:
// v--- 1 is in cache range
val ranged: Int = 1
val boxedRanged1: Int? = ranged
val boxedRanged2: Int? = ranged
println(boxedRanged1 === boxedRanged2) //true
// v--- 128 is out of cache range
val excluded: Int = 128
val boxedExcluded1: Int? = excluded
val boxedExcluded2: Int? = excluded
println(boxedExcluded1 === boxedExcluded2) //false
source to share