Kotlin: an array of generics
I am writing a B-tree that can have many keys in one node and I am facing a problem. When I create the Ints array , everything works fine:
class Node<K: Comparable<K>> (val t: Int) {
val keys: Array<Int?> = Array<Int?> (t*2-1, {null})
}
But I want to create a Generics Ks array :
class Node<K: Comparable<K>> (val t: Int) {
val keys : Array<K?> = Array<K?> (t*2-1, {null})
}
In this case, the compiler issues this error message:
'Kotlin: Cannot use 'K' as reified type parameter. Use a class instead.'
Question: How do I create a Generics array?
UPD: thanks for all the answers! MutableList seems to be a good solution for my purpose.
source to share
You can use instead List<K>
, it doesn't require types reified
.
To use shared parameters with Array<K>
you need a shared parameter reified
(so you can get its class)
You cannot use reified
with classes, only with functions, and functions must beinline
So I suggest you use it class
as late as possible, with specific or non- reified
typed types.
Meanwhile, you can use functions like these
inline fun <reified K : Comparable<K>> computeKeys(t: Int): Array<K?> =
Array(t * 2 - 1) { null }
source to share