为什么在Kotlin中启动新的Android活动需要Java类? [英] Why does starting a new Android activity in Kotlin require a Java class?

查看:102
本文介绍了为什么在Kotlin中启动新的Android活动需要Java类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆