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.

3

1 Answer 1

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

Very true, use List instead of Array as much as possible. Arrays on JVM are outdated :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.