Kotlin:泛型数组 [英] Kotlin: Array of Generics

查看:188
本文介绍了Kotlin:泛型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一棵B树,在一个节点中可能有很多键,但是遇到了问题.当我创建一个整数的数组时,一切正常:

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})
}

但是我想创建一个泛型数组 Ks :

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.'

问题是如何创建泛型数组?

UPD :感谢所有回复!看来 MutableList 是实现我目标的不错的解决方案.

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

推荐答案

您可以直接使用List<K>,它不需要您具有reified类型.

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

要将通用参数与Array<K>一起使用,您需要将通用参数设为reified(这样就可以得到它的类)

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

您不能将reified与类一起使用,而只能与函数一起使用,并且这些函数必须为inline

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

因此,我建议您尽可能晚地将class与具体或非reified泛型类型一起使用.

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 }

这篇关于Kotlin:泛型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆