Kotlin basic type auto packing problem solution
Kotlin basic type auto packing problem solution
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 method is to 1 display the byte code of kotlin! [write picture description here]( http://img.blog.csdn.net/20171013135245711?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvenhtMzE3MTIyNjY3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast )2 decompile kotlin bytecode into Java bytecode! [write picture description here]( http://img.blog.csdn.net/20171013135324119?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvenhtMzE3MTIyNjY3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast )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?
This "`?" ` 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
If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!