Ant*_*hov 4 arrays generics kotlin
我正在写一棵B树,它的一个节点可能有很多键,我遇到了一个问题。当我创建一个Int数组时,一切正常:
class Node<K: Comparable<K>> (val t: Int) {
val keys: Array<Int?> = Array<Int?> (t*2-1, {null})
}
Run Code Online (Sandbox Code Playgroud)
但我想创建一个泛型K数组:
class Node<K: Comparable<K>> (val t: Int) {
val keys : Array<K?> = Array<K?> (t*2-1, {null})
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,编译器会抛出以下错误消息:
'Kotlin: Cannot use 'K' as reified type parameter. Use a class instead.'
Run Code Online (Sandbox Code Playgroud)
问题是如何创建泛型数组?
UPD:感谢所有回复!看来MutableList对于我的目标来说是一个很好的解决方案。
您可以直接使用List<K>,它不需要您有reified类型。
要将泛型参数与 一起使用Array<K>,您需要泛型参数为reified(以便您可以获得它的类)
不能reified与类一起使用,只能与函数一起使用,并且函数必须是inline
因此,我建议您class尽可能晚地使用具体或非reified泛型类型。
同时,您可以使用这样的功能
inline fun <reified K : Comparable<K>> computeKeys(t: Int): Array<K?> =
Array(t * 2 - 1) { null }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2532 次 |
| 最近记录: |