fun main(arg: Array<String>) { var ints:Array<Int> = arrayOf(1, 2, 3) val any =Array<Any>(3){} copy(ints,any)//编译错误,因为Array<Int>不是Array<Any>的子类型 } fun copy(from :Array<Any>,to:Array<Any>){ assert(from.size==to.size) for (i in from.indices){ to[i]=from[i] } }
fun main(arg: Array<String>) { var ints:Array<Int> = arrayOf(1, 2, 3) val any =Array<Any>(3){} copy(ints,any)//编译通过 } fun copy(from :Array< out Any>,to:Array<Any>){ assert(from.size==to.size) for (i in from.indices){ to[i]=from[i] } }
上面是有out类型投射,我们声明的含义:from 不是一个单纯的数组,而是一个被限制投射的数组,也可以使用in关键字来投射一个类型