This question already has an answer here:
-
When we start new activity into kotlin why we put .java in intent instead of .kt
1 answer
If I want to start a new Activity in Android, I need to pass the Activity to an Intent. However, instead of just passing the Kotlin class like so:
val intent: Intent = Intent(this, SearchActivity::class)
I need to pass the Kotlin class as a Java class like this:
val intent: Intent = Intent(this, SearchActivity::class.java)
Why do I need to add this extra identifier since my SearchActivity
is a .kt file?
The second parameter to the Intent
constructor that you are using takes a java.lang.Class
object. SearchActivity::class
returns a kotlin.reflect.KClass
. You get a java.lang.Class
from that by accessing its java
property. Hence, you wind up with the somewhat odd syntax of SearchActivity::class.java
.
Here's an explanation.
Basically, ClassName::class
returns Kotlin's implementation of Class, KClass, which doesn't extend Java's Class. That's why ::class.java
is needed. java
is a getter in KClass, which returns a Java Class version of the KClass instance.
Check out the KClass Reference.