后续补充
code:
var x1: Int? = 127
var x2: Int? = 127
println("x1 === x2 : ${x1 === x2}")
var z1: Int? = 128
var z2: Int? = 128
println("z1 === z2 : ${z1 === z2}")
// 输出
x1 === x2 : true
z1 === z2 : false
分析:
查看Kotlin编译后的字节码
Integer x1 = 127
Integer x2 = 127
我们知道在java中 该代码会做自动装/拆包操作,编译器默认调用的是 Integer.valueOf(127)
查看Integer valueof 源码
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache.cache 缓存着 -128 - 127 的值