Anton Ostrouhhov
Anton Ostrouhhov

Reputation: 591

Kotlin: Array of Generics

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.

Upvotes: 4

Views: 2648

Answers (1)

Adel Nizamuddin
Adel Nizamuddin

Reputation: 821

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 }

Upvotes: 5

Related Questions