How can I check for generic type in Kotlin

phil picture phil · Oct 31, 2012 · Viewed 39.4k times · Source

I'm trying to test for a generic type in Kotlin.

if (value is Map<String, Any>) { ... }

But the compiler complains with

Cannot check for instance of erased type: jet.Map

The check with a normal type works well.

if (value is String) { ... }

Kotlin 0.4.68 is used.

What am I missing here?

Answer

Andrey Breslav picture Andrey Breslav · Oct 31, 2012

The problem is that type arguments are erased, so you can't check against the full type Map, because at runtime there's no information about those String and Any.

To work around this, use wildcards:

if (value is Map<*, *>) {...}