This question already has an answer here:
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?
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.
The second parameter to the
Intent
constructor that you are using takes ajava.lang.Class
object.SearchActivity::class
returns akotlin.reflect.KClass
. You get ajava.lang.Class
from that by accessing itsjava
property. Hence, you wind up with the somewhat odd syntax ofSearchActivity::class.java
.