Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin generic bounds for Class

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
like image 409
Ragunath Jawahar Avatar asked Jan 29 '15 15:01

Ragunath Jawahar


People also ask

How do you get a class from generic type Kotlin?

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.

What is generic class in Kotlin?

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.

What is out T in Kotlin?

"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.

How are bounds used with generics?

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.


4 Answers

javaClass has been deprecated. Use this instead:

val i = Intent(this@Activity, Activity::class.java)
startActivity(i)
like image 126
Ahmad Avatar answered Jan 04 '23 11:01

Ahmad


Use javaClass<MainActivity>() instead of MainActivity.javaClass

like image 44
Andrey Breslav Avatar answered Jan 04 '23 10:01

Andrey Breslav


Another option:

inline public fun <reified T : Activity> start() {
    startActivity(Intent(this, javaClass<T>()))
}
start<MainActivity>()
like image 27
naixx Avatar answered Jan 04 '23 11:01

naixx


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

like image 34
cesards Avatar answered Jan 04 '23 10:01

cesards