Why does starting a new Android activity in Kotlin

2019-03-03 15:19发布

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?

2条回答
唯我独甜
2楼-- · 2019-03-03 15:51

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-03 16:03

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.

查看更多
登录 后发表回答