Reputation: 2246
I am learning Kotlin and would like to understand how the compiled code gets executed, and how is it different from Java code execution with Android.
I also want to know why we write MainActivity::class.java
(class.java
) to reference class file.
Thank you!
Upvotes: 2
Views: 1139
Reputation: 170795
how is it different from Java code execution with Android
It isn't. Android doesn't execute Java code or Kotlin code. Instead there is the following chain:
Java/Kotlin/Scala/etc. compiler takes Java/Kotlin/Scala code and emits JVM bytecode in .class
files.
Android Gradle plugin takes JVM bytecode, converts it to Dalvik bytecode (using dx
program) and packs it into .apk
.
When the .apk
file is installed on device, ART converts Dalvik bytecode it contains to machine code.
It's that machine code (and/or Dalvik bytecode) which is executed. ART has no idea which language source code was in at step 1 and doesn't care.
I also want to know why we write MainActivity::class.java (class.java) to reference class file.
You don't. You write it to reference the Class
object corresponding to the MainActivity
class.
Upvotes: 10
Reputation: 243
Basically Kotlin is compiled to the same byte code as Java.
You can find Kotlin tutorials all over the web. But they never explain very much about the generated bytecode other than 'it is jvm bytecode'. So one would imagine that there is no big difference to Java-compiled bytecode.
I can imagine that one difference is that Kotlin augments the generated bytecode with annotations so as to enable Kotlin specific language features. This is probably also the reason why Kotlin has its own KClass type. It is probably capable of reading the kotlin specific class annotations. In effect there are 2 types that represent a class (KClass and Class). The old-school Class type instance is reference via class.java.
Also note that Kotlin can be compiled to other languages than JVM bytecode. In those other cases there will be no Class reference, but still a KClass reference.
A good starting point for tutorials is https://kotlinlang.org
Upvotes: 1