Inspired by Create generic 2D array in Kotlin, I have the following code that creates a generic class with an array of type T. However, once I add an upper bound, I get a compile error. Is there a way to do this?
//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)
}
The compile errors are:
- Type parameter bound for T in constructor GenericClass>(size: Int, arrayFactory: (Int) -> Array) is not satisfied: inferred type T? is not a subtype of Comparator