Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

nullable - Kotlin boxed Int are 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, the Int will be mapped to java int/Integer depending on its context. If Int is a generic argument, then its mapped type is Integer. Otherwise, it is a primitive type int. for example:

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

Secondly, boxing an Int to an Int? is same behavior as java boxing an int to an Integer, for example:

val a:Int = 1   // int a = 1;
val b:Int? = a; // Integer b = a;

Why the boxed Integers are not the same?

This is because Integer only caching values in the range [-128, 127]. the the variable a 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:

//                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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...