sortedWith()扩展函数中Kotlin的逆变
在Kotlin sortedWith extension中,比较器的方差定义为:sortedWith()扩展函数中Kotlin的逆变,kotlin,generics,Kotlin,Generics,在Kotlin sortedWith extension中,比较器的方差定义为: public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T> public-fun-Iterable.sortedWith(comparator:comparator):列表 据我所知,这是为了能够使用超级类型的比较器来比较实际类型: val comparator: Co
public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T>
public-fun-Iterable.sortedWith(comparator:comparator):列表
据我所知,这是为了能够使用超级类型的比较器来比较实际类型:
val comparator: Comparator<Number> = Comparator { o1: Number, o2: Number ->
o1.toInt().compareTo(o2.toInt())
}
val intList: List<Int> = listOf(4, 7)
intList.sortedWith(comparator)
val-comparator:comparator=comparator{o1:Number,o2:Number->
o1.toInt().compareTo(o2.toInt())
}
val intList:List=listOf(4,7)
intList.sortedWith(比较器)
但这在不引入对冲的情况下也会起作用:
fun <T> Iterable<T>.sortedWithMock(comparator: Comparator<T>) {
}
val comparator: Comparator<Number> = Comparator { o1: Number, o2: Number ->
o1.toInt().compareTo(o2.toInt())
}
val intList: List<Int> = listOf(4, 7)
intList.sortedWithMock(comparator)
fun Iterable.sortedWithMock(比较器:比较器){
}
val比较器:比较器=比较器{o1:Number,o2:Number->
o1.toInt().compareTo(o2.toInt())
}
val intList:List=listOf(4,7)
intList.sortedWithMock(比较器)
我是否遗漏了什么,或者在sortWith()中实际上不需要逆变声明
在Java中,比较器的反差允许函数返回一个
列表
,其中T
是列表
的原始类型,而不是比较器
的类型
如果您充实您的模拟函数以返回列表
,那么当您使用比较器
调用该函数时,T
类型将是Number
,而不是Int
,因此返回的列表
类型比原始的Iterable
类型具体。这是因为要调用模拟函数,它必须将Iterable
的协变类型隐式向上转换为与比较器的不变类型匹配的类型
相反,标准库函数能够隐式向下转换比较器的逆变类型,以匹配Iterable的逆变类型。比较器的逆变允许函数返回一个列表,其中T
是列表的原始类型,不是比较器的类型
如果您充实您的模拟函数以返回列表
,那么当您使用比较器
调用该函数时,T
类型将是Number
,而不是Int
,因此返回的列表
类型比原始的Iterable
类型具体。这是因为要调用模拟函数,它必须将Iterable
的协变类型隐式向上转换为与比较器的不变类型匹配的类型
相反,标准库函数能够隐式向下转换比较器的逆变类型,以匹配Iterable的
类型
public class Test {
// Comparator<? super E> required
static <E> void sort(List<E> l, Comparator<E> c) {
}
static class cn implements Comparator<Number> {
@Override
public int compare(Number o1, Number o2) {
return 0;
}
}
public static void main(String []args){
List<Integer> l = new ArrayList<Integer>();
Comparator<Number> cn = new cn();
sort(l, cn);
}
}