您现在的位置是:首页 > 文章详情

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

日期:2018-04-04点击:667

一、首先来看一个例子

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:型变点违例

原文链接:https://yq.aliyun.com/articles/614548
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章