Aliy
Aliy

Reputation: 406

Kotlin generics Checking class type with when

I have tried to check the type of generic T but struggling to do that

How can i check the type of generic T

Upvotes: 0

Views: 325

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170723

In addition to gidds' answer; it looks like T is a type parameter of your class (as opposed to method), so you can add Class<T> to its constructor parameters:

class YourClass<T>(/* your current parameters */, private val classOfT: Class<T>) : ... {
    override fun createAd(dto: AdvertDTO<T>): Ad {
        when(classOfT) ...
    }
}

You can also optionally add a helper function to construct it using reified:

inline fun <reified T> YourClass(...) = YourClass(..., T::class)

Upvotes: 1

gidds
gidds

Reputation: 18557

You can't.

This is a result of type erasure: although the compiler type-checks all generics carefully, the generated code knows nothing about the type parameters, so they're not available at runtime.

(That is in turn a consequence of how generics were added to Java in the most backward-compatible way.)

If you need to know the type at runtime, the usual solution is either to add it in as an extra parameter that you pass, or to use Kotlin's reified modifier as the error hints (which basically does the same thing, in a more concise and compatible way).  However, if you're overriding an existing method, that might not be possible.

Or you can tweak the design so that you don't need to know the type explicitly, perhaps by usingq polymorphism.  (That's not always possible, either — but if it is, it can make the code much simpler and more robust.)

Upvotes: 2

Related Questions