The following generics doesn't compile. What is semantically wrong here?
Function call
start(MainActivity.javaClass) // <== Doesn't compile
Method Definition
// Definition
public fun <T : Activity> start(activityClass: Class<T>) {
startActivity(Intent(this, activityClass))
}
Compiler Error
Error:(43, 9) Type parameter bound for T in fun <T : android.app.Activity>
start(activityClass: java.lang.Class<T>): kotlin.Unit is not satisfied:
inferred type com.mobsandgeeks.hellokotlin.MainActivity.
<class-object-for-MainActivity> is not a subtype of android.app.Activity
There are no direct ways to do this in Kotlin. In order to check the generic type, we need to create an instance of the generic class<T> and then we can compare the same with our class.
Generics means we use a class or an implementation in a very generic manner. For example, the interface List allows us for code reuse. We are able to create a list of Strings, of integer values and we will have the same operations even if we have different types.
"Out" keyword is extensively used in Kotlin generics. Its signature looks like this − List<out T> When a type parameter T of a class C is declared out, then C can safely be a super type of C<Derived>. That means, a Number type List can contain double, integer type list.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
javaClass
has been deprecated. Use this instead:
val i = Intent(this@Activity, Activity::class.java)
startActivity(i)
Use javaClass<MainActivity>()
instead of MainActivity.javaClass
Another option:
inline public fun <reified T : Activity> start() {
startActivity(Intent(this, javaClass<T>()))
}
start<MainActivity>()
The only way it worked for me is doing this:
val intent = Intent(this, NextActivity::class.java)
startActivity(intent)
None of the other solutions have worked, including the usage of javaClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With