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
sortedWith()扩展函数中Kotlin的逆变_Kotlin_Generics - Fatal编程技术网

sortedWith()扩展函数中Kotlin的逆变

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

在Kotlin sortedWith extension中,比较器的方差定义为:

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);
    }
}