How to check generic type in Kotlin?

前端 未结 4 667
温柔的废话
温柔的废话 2020-12-29 21:47

I have class

class Generic()

and this code is\'t correct

fun typeCheck(s: SuperType): Unit {
               


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 22:17

    Generic types are not reified on the JVM at runtime, so there's no way to do this in Kotlin. The warning is correct because the compiler can't possibly generate any instruction that will fail when the cast is done, so the cast is unchecked, meaning that the program may or may not break at some point later instead.

    A related feature which might be of use is reified type parameters in inline functions. Classes can't have reified type parameters though, so if you elaborate a bit more on your use case, I can try helping you achieve what you seem to need.

提交回复
热议问题