如何在Kotlin中检查泛型? [英] How to check generic type in Kotlin?

查看:203
本文介绍了如何在Kotlin中检查泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上课

class Generic<T : SuperType>()

此代码不正确

fun typeCheck(s: SuperType): Unit {
            when(s){
                is T -> //do some thin
            }
        }

但是将s强制转换为T s as T类型显示警告-不安全的强制转换.
如何检查sT类型?

but cast s to type T s as T show warning - unsafe cast.
How check that s is type T?

推荐答案

泛型类型在运行时未在JVM上实现统一化,因此Kotlin中无法做到这一点.该警告是正确的,因为在强制转换完成后编译器不可能生成任何会失败的指令,因此不进行强制转换,这意味着程序以后可能会或可能不会中断.

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.

这篇关于如何在Kotlin中检查泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆