Generics 为什么Int是Kotlin中compariable的子类型,而HashMap不是compariable
我正在通读这本书,发现这个说法我不理解。有人能解释一下吗 给定Generics 为什么Int是Kotlin中compariable的子类型,而HashMap不是compariable,generics,kotlin,Generics,Kotlin,我正在通读这本书,发现这个说法我不理解。有人能解释一下吗 给定 fun <T : Comparable<T>> sort(list: List<T>) { ... } 然后 这是因为kotlin.Int实现了kotlin.Comparable,所以满足了函数sort中类型T的上限,因为T的列表是Int的列表 相反,HashMap没有实现Compariable,因此函数sort中类型t的上限不满足,因为t的列表是HashMap的列表 要使其具有可比性,您可以
fun <T : Comparable<T>> sort(list: List<T>) { ... }
然后
这是因为kotlin.Int实现了kotlin.Comparable,所以满足了函数sort中类型T的上限,因为T的列表是Int的列表
相反,HashMap没有实现Compariable,因此函数sort中类型t的上限不满足,因为t的列表是HashMap的列表
要使其具有可比性,您可以创建自定义HashMap,该HashMap也具有可比性:
类CompariableHashMap:HashMap,Compariable{
覆盖有趣的CompareTother:HashMap:Int{
//实现比较。
}
}
哈哈哈,我想我应该打开一个IDE,同时查找Int和HashMap。我认为这一主张完全基于所提出的内容,没有考虑进一步的背景。谢谢
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>>