为什么 Int 是 Kotlin 中可比较的子类型<Int>,但 HashMap 不是可比较<HashMap>的子类型



我正在阅读Kotlin文档,发现我不理解这一说法。有人能解释一下吗?

给定

fun <T : Comparable<T>> sort(list: List<T>) {  ... }

然后

sort(listOf(1, 2, 3)) // OK. Int is a subtype of Comparable<Int>
sort(listOf(HashMap<Int, String>())) // Error: HashMap<Int, String> is not a subtype of Comparable<HashMap<Int, String>>
这是因为kotlin.Int实现了kotlin.Comparable<Int>,所以函数sort中类型T的上界得到满足,因为T的列表是Int的列表。

相反,HashMap<K, V>不实现Comparable<HashMap<K, V>>,因此函数sort中类型T的上界不满足,因为T的列表是HashMap<Int, String>的列表。

要使其成为Comparable,您可以创建自定义HashMap,也就是Comparable:

class ComparableHashMap<K, V>: HashMap<K, V>(), Comparable<HashMap<K, V>> {
override fun compareTo(other: HashMap<K, V>): Int {
// Implement comparison.
}
}

最新更新