Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for generic type in Kotlin

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?

like image 446
phil Avatar asked Oct 31 '12 09:10

phil


People also ask

How do you find the type of generic type?

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.

How do I check my Kotlin data type?

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.

When can you use generic Kotlin?

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.


1 Answers

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<*, *>) {...} 
like image 122
Andrey Breslav Avatar answered Oct 05 '22 18:10

Andrey Breslav