Analysis of automatic packing of kotlin basic types
problem
When the official kotlin document introduces basic types, it explains that basic types are automatically boxed in some cases. However, there is no detailed description of how and when to pack. Only an example is provided, as follows:
For the above code, it took a lot of effort to write a lot of demos to figure it out. Next, let's understand how kotlin performs the packing operation through a few simple chestnuts
The first chestnut
Give you some tips. If you don't understand how kotlin compiles and runs, we can decompile it into Java bytecode first. We're familiar with Java. The specific approach is
1 displays the bytecode of kotlin
2 decompile kotlin bytecode into Java bytecode
Using this method, decompile the above test1 () method to obtain the following bytecode
It can be seen that the kotlin compiler simply regards I as a basic type short and prints it
Another chestnut
See the difference between test1 and test2?? One more in test2? val i: Int? = 1000 the "`?" ` means that this I can be assigned null. Since it can be null, it can not be the original type, but only an object. Therefore, kotlin will automatically carry out boxing operation for it. Therefore, after decompiling test2, we will get the following bytecode
analysis
After understanding the above two chestnuts, you can understand it by looking back at the official demo. We might as well write a similar code ourselves
After decompilating into Java bytecode, the result is consistent with our conjecture:
summary
Note: in kotlin, character type is not a basic numeric type, but an independent data type. Instead of using java keywords such as int and double, the above expression of shaping types uses encapsulated classes because everything in kotlin is an object (not like the basic types in Java). When we use integer numbers in our code, kotlin will automatically pack them
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.