Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 为什么Int是Kotlin中compariable的子类型,而HashMap不是compariable_Generics_Kotlin - Fatal编程技术网

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>>