We have to write this line with the extension .java although its extension is .kt I think Kotlin file converts into the java file but the java also converts in byte code so we can also use .class file If the Kotlin code converts into the java code.
NextActivity::class.java
to NextActivity::class.kt //not worked
btn?.setOnClickListener {
startActivity(Intent(this, NextActivity::class.java))
}
So the question is why we write the .java in NextActivity::class.java
Question arises from here.
By using ::class , you get an instance of KClass. It is Kotlin Reflection API, that can handle Kotlin features like properties, data classes, etc. By using ::class. java , you get an instance of Class.
:: is just a way to write a lambda expression basically we can use this to refer to a method i.e a member function or property for example class Person (val name: String, val age: Int) Now we can write this to access the person which has the maximium age.
What's critical to Kotlin is that you can use any existing Java libraries, opening up a plethora of powerful code to reuse. This includes the standard library and any third-party libraries and frameworks, whether it be Spring,1 JUnit,2 or the Android Software Development Kit (SDK).
If your question is can you use kotlin files in java files and vice versa then the answer is yes.
You are calling Java code from Kotlin. Intent is Java class in Android.
Doc: https://kotlinlang.org/docs/reference/reflection.html#class-references
Note that a Kotlin class reference is not the same as a Java class reference. To obtain a Java class reference, use the .java property on a KClass instance.
You cannot pass Kotlin class reference to Java (Intent in your case) and so you have to pass Java class reference.
From the interop doc: https://kotlinlang.org/docs/reference/java-interop.html#java-reflection
Java reflection works on Kotlin classes and vice versa. As mentioned above, you can use instance::class.java, ClassName::class.java or instance.javaClass to enter Java reflection through java.lang.Class.
Because you want to access the methods of the Java Class.
I think they are not reimplemented from scratch in Kotlin so, in order to access them, you have to "reflect" your kotlin class to a Java one.
NextActivity::class
returns the KClass
reference and the KClass
has the property java
and the Intent
contructor signature is Intent(Context packageContext, Class cls)
so the second parameter is Class
type So the final answer would be this is not the extension this is just property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With