Johann
Johann

Reputation: 29875

Check if passed parameter is a type of class

I want to call the following function:

fun <T> isCurrentActivity( t: Class<T>): Boolean {
    return (currentActivity != null) &&  (currentActivity is t)
}

if (isCurrentActivity(MainActivity::class.java)) {

}

But t is an unresolved reference. How can I fix that? I can't use an inline reified function because the function needs to be publicly available.

Upvotes: 1

Views: 1260

Answers (1)

Cililing
Cililing

Reputation: 4763

The problem is that JVM erase generic type, so type of parameter T is not accessible at runtime.

That's why in Java a popular pattern is passing instance of Class<T> as a param. It's not required in Kotlin, because in Kotlin we can define reified type and that type is accessible at runtime.

Example:

inline fun <reified T> isCurrentActivity(): Boolean {
    return (currentActivity != null) &&  (currentActivity is T)
}

fun example() {
    if (isCurrentActivity<MainActivity>()) {
        // it is!
    }
}

Requirements for marking T as reified is marking a function as inline. See more at docs: https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters

An example above is a "kotlin way to do that". If you would like to stay with "java like code" the mistake you do is that you try to check if a currentActivity is an instance of variable - what is not possible. Correct way would be:

fun <T> isCurrentActivity(t: Class<T>): Boolean {
    return (currentActivity != null) && currentActivity.javaClass == t
}

Please see @gidds comment about the check above.

But, I still recommend using reified type parameter, as it's a really nice way to check the type.

Upvotes: 2

Related Questions