How can I check for generic type in Kotlin
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<*, *>) {...}
I think this is more appropriate way
inline fun <reified T> tryCast(instance: Any?, block: T.() -> Unit) {
if (instance is T) {
block(instance)
}
}
Usage
// myVar is nullable
tryCast<MyType>(myVar) {
// todo with this e.g.
this.canDoSomething()
}
Another shorter approach
inline fun <reified T> Any?.tryCast(block: T.() -> Unit) {
if (this is T) {
block()
}
}
Usage
// myVar is nullable
myVar.tryCast<MyType> {
// todo with this e.g.
this.canDoSomething()
}