为什么在Kotlin中启动新的Android活动需要Java类? [英] Why does starting a new Android activity in Kotlin require a Java class?
问题描述
如果我想在Android中启动新的Activity,则需要将Activity传递给Intent.但是,不仅仅是像这样传递Kotlin类:
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)
我需要将Kotlin类作为Java类传递:
I need to pass the Kotlin class as a Java class like this:
val intent: Intent = Intent(this, SearchActivity::class.java)
由于我的SearchActivity
是.kt文件,为什么需要添加此额外的标识符?
Why do I need to add this extra identifier since my SearchActivity
is a .kt file?
推荐答案
您正在使用的Intent
构造函数的第二个参数采用java.lang.Class
对象. SearchActivity::class
返回kotlin.reflect.KClass
.通过访问其java
属性,可以从中获得java.lang.Class
.因此,您会使用SearchActivity::class.java
有点古怪的语法.
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
.
这篇关于为什么在Kotlin中启动新的Android活动需要Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!