I have a generically typed class Builder<T> that takes a constructor argument Class<T> so I can keep the type around. This is a class that I use a lot in java code so I don't want to change the signature. When I try to use the constructor like this:

Builder<List<Number>>(List<Number>::class)

I get an error: "Only classes are allowed on the left hand side of a class literal"

有办法解决这个问题吗?

我理解整个类型擦除问题,我真的只是想让编译器满意.

推荐答案

Due to generic type erasure List class has a single implementation for all its generic instantiations. You can only get a class corresponding to List<*> type, and thus create only Builder<List<*>>.

该生成器实例适用于构建something个列表.同样,由于类型擦除,您可以在未经判断的强制转换的帮助下自行决定:

Builder(List::class.java) as Builder<List<Number>>
Builder(List::class.java as Class<List<Number>>)

Another approach is to create inline reified helper function:

inline fun <reified T : Any> Builder() = Builder(T::class.java)

and use it the following way:

Builder<List<Number>>()

Kotlin相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

&x是T&q;和&q;(x为?T)!=空(&Q;)?

用vararg替换列表的设计弃用警告

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

Kotlin 协程按顺序执行,但仅在生产机器上执行

Kotlin 数据类中的大量参数

gradle 如何 Select 以-jvm结尾的库?

Kotlin 中的密封和内部有什么区别?

Android 在将 androidx 生物识别更新为 1.0.0-alpha04 后崩溃

模拟异常 - 没有找到答案

在协程中等待侦听器内的数据

Kotlinwhen表达式在使用主题时是否支持复合布尔表达式?

如何修复 ViewPager2 中的Design assumption violated错误?

无法创建类 ViewModel kotlin 的实例

如何处理 Kotlin 中的异常?

Firestore - 如何在 Kotlin 中排除数据类对象的字段

在 Kotlin 中创建非绑定服务

如何将vararg作为数组传递给Kotlin中的函数?

将字符串编码为Kotlin中的UTF-8

WebFlux 功能:如何检测空 Flux 并返回 404?