Kotlin的型变解析(协变、逆变和不变)

2023-11-06

一、首先来看一个例子

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") //To change initializer of created properties use File | Settings | File Templates.

     fun contains(element: @UnsafeVariance E): Boolean {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

     fun containsAll(elements: Collection<E>): Boolean {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

二、看一下协变、逆变和不变的例子

import java.util.*

/**
 * @author:wangdong
 * @description:协变、逆变、不变
 */

fun main(args: Array<String>) {

    //定义个协变
    //List 不是java.util中的list
    //定义一个numberlist的引用。
    //List<number>是只读的接口
    //number是int的父类,所以List<Number>是List<Int>的父类
    val numberList: List<Number> = listOf(1,3,5)
    //public interface List<out E> : Collection<E> {

    //定义一个逆变的例子
    //恰恰相反public interface Comparable<in T> {,是可写的接口
    //所以Comparable<Int> 是 Comparable<Any>的父类
    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
        }
    }

    //定义一个不变的例子
    //报错部分,都说明MutableList<T>不是mutableListOf<非T>的父类
    //只有在T与T相同的情况下,才是ok的
    //val numberArrayList: MutableList<Number> = mutableListOf<Int>(1,5,7)
    //val numberArrayList: MutableList<Int> = mutableListOf<Number>(1,5,7)
    val numberArrayList: MutableList<Int> = mutableListOf<Int>(1,5,7)
    //MutableList接口public interface MutableList<E> : List<E>, MutableCollection<E> {
    //既没有out,也没有in,所以这个接口是可读写的,所以它是不变的
}

三、协变、逆变和@UnsafeVariance
1.协变点:返回值类型是泛型参数类型
2.逆变点:入参类型是泛型参数类型
3.@UnsafeVariance:型变点违例

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Kotlin的型变解析(协变、逆变和不变) 的相关文章

随机推荐