这是因为
我正在阅读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.
}
}