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?
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
You can use b::class. simpleName that will return type of object as String . You don't have to initialize type of a variable and later you want to check the type of variable.
Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety. A generic type is a class or method that is parameterized over types.
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<*, *>) {...}
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