【发布时间】:2016-07-11 05:03:17
【问题描述】:
受Create generic 2D array in Kotlin 的启发,我有以下代码,它创建了一个类型为 T 的数组的泛型类。但是,一旦我添加了一个上限,就会出现编译错误。有没有办法做到这一点?
//This code compiles:
class GenericClass<T> protected constructor(size : Int, arrayFactory: (Int) -> Array<T>) {
companion object {
inline fun <reified T> invoke(size : Int)
= GenericClass(size, { size -> arrayOfNulls<T>(size) })
}
val array = arrayFactory(size)
}
//Compile errors:
class GenericClass<T : Comparator<T>> protected constructor(size : Int, arrayFactory: (Int) -> Array<T>) {
companion object {
inline fun <reified T : Comparator<T>> invoke(size : Int)
= GenericClass(size, { size -> arrayOfNulls<T>(size) })
}
val array = arrayFactory(max)
}
编译错误是:
- 构造函数 GenericClass 中为 T 绑定的类型参数>(size: Int, arrayFactory: (Int) -> Array) 不满足:推断类型 T?不是 Comparator 的子类型
【问题讨论】: