When you introduce the basic types in the official documentation for Kotlin, we are told that in some cases the base type is automatically boxed. However, the details of how to do the boxing, and when to do not provide a detailed description. Just provide an example, as follows:
Val a:int = 10000
print (a = = = a)//prints ' true '
val boxeda:int? = a
val anotherboxeda:int? = a
print ( Boxeda = = Anotherboxeda)//!!! Prints ' false '!!!
1 2 3 4 5
For the above code, waste a great effort to write a lot of demo to get clear. Next, let's start by using a few simple chestnuts to understand how Kotlin is the first chestnut for boxing operations.
Fun Main (args:array<string>) {
test1 ()
}
Fun test1 () {
val i:int = 1000 println
(i)
}
1 2 3 4 5 6 7 8
To provide you with a bit of skill, we can not understand how Kotlin is compiled to run the case, we could first compile it into Java bytecode, for Java we are very adept at it. The practice is
1 to display Kotlin byte code
2 decompile the Kotlin byte code into Java byte code
In this way, the above Test1 () method is compiled to produce the following bytecode
public static final void Test1 () {short
i = 1000;
System.out.println (i);
}
1 2 3 4
You can see that the Kotlin compiler sees I as simply a basic type of short and prints it and then lifts a chestnut .
Fun Main (args:array<string>) {
test2 ()
}
Fun test2 () {
val i:int? = 1000 println
(i)
}
1 2 3 4 5 6 7 8
See the difference between Test1 and test2? One more in the Test2 ?
Val i:int? = 1000
This "'?" ' Means this I can be assigned null, since it can be null, it cannot be the original type, it can only be an object, so Kotlin will automatically boxing it. So after we decompile the test2, we get the following byte code
public static final void Test2 () {
Integer i = integer.valueof (1000);
System.out.println (i);
}
1 2 3 4
Analysis
Understanding the above two small chestnuts, after looking back at the official demo, you can understand. We may as well write a similar code ourselves
Fun Test3 () {
//kotlin does not automatically boxing
val i:int = 1000
println (i)
//Because both J and K are manipulated as objects, the I is boxed and then copied to J, K
val j:int = i
val k:int? = i
println (j = = k)
}
1 2 3 4 5 6 7 8 9 10 11-12
The result, after being compiled into Java bytecode, is consistent with our conjecture:
public static final void Test3 () {short
i = 1000;
System.out.println (i);
Integer j = integer.valueof (i);
Integer k = integer.valueof (i);
Boolean VAR3 = j = = k;
System.out.println (VAR3);
}
1 2 3 4 5 6 7 8
Summary
Note: In Kotlin, the character type is not a basic numeric type, it is a separate data type.
The type of shaping above does not use keywords in Java such as int, double, and instead uses encapsulated classes to denote that this is because everything in Kotlin is an object (there is no basic type in Java). When we use reshaping numbers in our code, Kotlin automatically boxing them up.