Reputation: 9123
An intent in Kotlin:
val intent = Intent(this, OtherActivity::class.java)
why can't it just be:
val intent = Intent(this, OtherActivity)
?
Upvotes: 2
Views: 1055
Reputation: 28228
Using ::class
, Kotlin supplies a KClass
, which can be used for various things. However, there are still Java packages which use Class
instead, and among those is Intent. A KClass is not a Class, which means Kotlin needs to have a way to access the regular Java Class.
The Intent
class is originally written in Java, which means it uses a Class
. OtherActivity::class
returns a KClass, and a KClass can't be passed as a Class
.
SomeClass::class.java
exists for interop purposes. You can also use a Class
instead of KClass
in your Kotlin code; you won't get warnings about that like you'd get about for an instance Object
over Any
. But you still periodically need a Class
with Java interop.
Why specifically they went with ::class.java
is not something anyone can answer, aside the developers of the language itself.
Upvotes: 2
Reputation: 2975
if you are okay with a little bit of namespace polution and this is a real concern in your team you can allways declare the following top level function:
inline fun <reified T> Intent(context: Context){
return Intent(context, T::class.java)
}
Which you would call doing the following:
val intent = Intent<MyActivity>(this)
Or if you want you can declare it as an extension function on Context:
inline fun <reified T> Context.Intent(){
return Intent(this, T::class.java)
}
An use it directly like this:
val intent = Intent<MyActivity>()
Upvotes: 1
Reputation: 12463
The second argument of that Intent constructor requires the class of the Activity you want to create. While it would be convenient to get the class just by using the class name OtherActivity
, Java (and Kotlin) syntax does not support this.
Instead, Java provides the .class
syntax (OtherActivity.class
) and Kotlin provides::class
for the Kotlin class, and ::class.java
(OtherActivity::class.java
) for the Java class, which is what the Intent constructor needs.
Upvotes: 5
Reputation: 2288
Because Intent is a java class and expects an Android Context and a Java Class (The activity) as the arguments.
Upvotes: 1