Kotlin

Kotlin泛型

2018-09-01  本文已影响90人  agile4j

作者:刘仁鹏
参考资料:
1.https://www.yiibai.com/kotlin/generics.html
2.https://www.jianshu.com/p/832b9548b331


1.型变的概念

//List<Object> list = new ArrayList<String>(); //编译期错误:Incompatible types.
List<? extends Object> list = new ArrayList<String>(); //OK
List<? super String> list2 = new ArrayList<Object>(); //OK

2.PECS

public static <T> void copy(List<? super T> dest, List<? extends T> src) {
    // 校验略
    ListIterator<? super T> di = dest.listIterator();
    ListIterator<? extends T> si = src.listIterator();
    while (si.hasNext()) {
        di.next();
        T element = si.next(); // src extent 生产者 作为方法返回值类型是安全的
        di.set(element); // dest super 消费者 作为方法参数类型是安全的
    }
}

3.声明处型变

abstract class Supplier<out T> {
    abstract fun get(): T
    //abstract fun set(t: T) 
    //编译期错误:Type parameter T is declared as 'out' but occurs in 'in' position in type T
}

abstract class Customer<in T> {
    abstract fun set(t: T)
    //abstract fun get(): T 
    //编译期错误:Type parameter T is declared as 'in' but occurs in 'out' position in type T
}

4.类型投影

abstract class Container<T>(val size: Int) {
    abstract fun get(index: Int): T
    abstract fun set(index: Int, value: T)
}
fun copy(from: Array<out Any>, to: Array<Any>) {
    // 校验略
    for (i in from.indices) {
        to[i] = from[i]
        //from[i] = null 
        //编译期错误:Out-projected type 'Array<out Any>' prohibits the use of 'public final operator fun set(index: Int, value: T): Unit defined in kotlin.Array
    }
}

5.星投影

  1. Function< *, String >表示Function< in Nothing, String >
  2. Function< Int, * >表示Function< Int, out Any? >
  3. Function< *, * >表示Function< in Nothing, out Any? >

end

上一篇下一篇

猜你喜欢

热点阅读