一、首先来看一个例子
import java.util.*
/**
* @author:wangdong
* @description:型变
*/
fun main(args: Array<String>) {
}
/**
* 定义一个类,实现了List接口
* 协变out(返回值只读类型),逆变in(通常是写入的),可读可写就是不变了
*/
class MyLisøt<in E>{
val size: Int
get() = TODO("not implemented")
fun contains(element: @UnsafeVariance E): Boolean {
TODO("not implemented")
}
fun containsAll(elements: Collection<E>): Boolean {
TODO("not implemented")
}
}
二、看一下协变、逆变和不变的例子
import java.util.*
/**
* @author:wangdong
* @description:协变、逆变、不变
*/
fun main(args: Array<String>) {
val numberList: List<Number> = listOf(1,3,5)
val intComparable: Comparable<Int> = object: Comparable<Any>{
/**
* Compares this object with the specified object for order. Returns zero if this object is equal
* to the specified [other] object, a negative number if it's less than [other], or a positive number
* if it's greater than [other].
*/
override fun compareTo(other: Any): Int {
return 0
}
}
val numberArrayList: MutableList<Int> = mutableListOf<Int>(1,5,7)
}
三、协变、逆变和@UnsafeVariance
1.协变点:返回值类型是泛型参数类型
2.逆变点:入参类型是泛型参数类型
3.@UnsafeVariance:型变点违例