如果类型参数受另一个类型参数的限制,则类型参数不能有任何其他限制:这是什么意思以及如何解决它?
Type parameter cannot have any other bounds if it's bounded by another type parameter: what does this mean and how to resolve it?
我在 kotlin 中实现自定义列表 class MyList<T>
。在那,我想添加 insertSorted
函数,它按排序顺序将一个新元素插入到列表中。为此,T
必须实现比较器。所以该函数的原型将是 fun <C> insertSorted(ele: C) where C:T, C:Comparable<T>
但这给了我 Type parameter cannot have any other bounds if it's bounded by another type parameter 错误。我不明白这个错误是什么。另外, 问题对我帮助不大。
PS:我传递给该函数的类型声明为 class MyClass : Comparator<MyClass>
。所以我猜 where C:T, C:Comparator<T>
是有效的。
错误的意思,看这个问题:
但是如果您的自定义列表包含 T
类型的元素并且您想比较它们,那么 T
应该实现 Comparable<T>
.
这就是您所需要的:
class MyList<T: Comparable<T>> {
fun insertSorted(ele: T) {
}
}
我在 kotlin 中实现自定义列表 class MyList<T>
。在那,我想添加 insertSorted
函数,它按排序顺序将一个新元素插入到列表中。为此,T
必须实现比较器。所以该函数的原型将是 fun <C> insertSorted(ele: C) where C:T, C:Comparable<T>
但这给了我 Type parameter cannot have any other bounds if it's bounded by another type parameter 错误。我不明白这个错误是什么。另外,
PS:我传递给该函数的类型声明为 class MyClass : Comparator<MyClass>
。所以我猜 where C:T, C:Comparator<T>
是有效的。
错误的意思,看这个问题:
但是如果您的自定义列表包含 T
类型的元素并且您想比较它们,那么 T
应该实现 Comparable<T>
.
这就是您所需要的:
class MyList<T: Comparable<T>> {
fun insertSorted(ele: T) {
}
}