4

I'm writing a B-tree, which may have many keys in one node, and I have encountered a problem. When I create an array of Ints 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 an array of Generics Ks:

class Node<K: Comparable<K>> (val t: Int) {
    val keys : Array<K?> = Array<K?> (t*2-1, {null})
}

In this case compiler throws this error message:

'Kotlin: Cannot use 'K' as reified type parameter. Use a class instead.'

The question is How to create an array of Generics?

UPD: Thx for all the replies! It seems that MutableList is nice solution for my objective.

Anton Ostrouhhov
  • 591
  • 1
  • 4
  • 7
  • 1
    See: [How to create a generic array in Java?](http://stackoverflow.com/q/529085/7079453) – F. George Mar 29 '17 at 12:46
  • 1
    Using an ArrayList instead of an array is a better option if you are not doing performance-critical operations. – Naetmul Mar 29 '17 at 13:04
  • Possible duplicate of [Create generic 2D array in Kotlin](http://stackoverflow.com/questions/28548647/create-generic-2d-array-in-kotlin) – miensol Mar 29 '17 at 13:10

1 Answers1

5

You can just use List<K> instead, it doesn't require you to have reified types.

To use generic parameters with Array<K>, you need the generic parameter to be reified (so that you can get it's class)

You can't use reified with classes, only with functions, and the functions must be inline

So I'd suggest that you use a class as late as possible, with concrete or non-reified generic types.

Meanwhile, you can use functions like these

inline fun <reified K : Comparable<K>> computeKeys(t: Int): Array<K?> =
    Array(t * 2 - 1) { null }
Adel Nizamuddin
  • 823
  • 14
  • 31
  • Very true, use `List` instead of `Array` as much as possible. Arrays on JVM are outdated :( – voddan Mar 30 '17 at 13:12