How can I check for generic type in Kotlin

与世无争的帅哥 提交于 2019-11-28 21:54:55

问题


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?


回答1:


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<*, *>) {...}



回答2:


JVM removes the generic type information. But Kotlin has reified generics. If you have a generic type T, you can mark type parameter T of an inline function as reified so it will be able to check it at runtime.

So you can do:

inline fun <reified T> checkType(obj: Object, contract: T) {
  if (obj is T) {
    // object implements the contract type T
  }
}



回答3:


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()
}


来源:https://stackoverflow.com/questions/13154463/how-can-i-check-for-generic-type-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!