在学习kotlin
泛型型变时,写了以下代码
val list2 = mutableListOf<Int>(4,4,5)
val list : MutableList<out Number> = list2
然后尝试了一下错误的写法
val list3 : MutableList<Number> = list2//error
发现以下代码不会报错
val list3 : MutableList = list2.toMutableList()
通过源码可以看到数据类型没有变化
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collectionextends E> c) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}