1. 程式人生 > >kotlin 泛型中型別投射

kotlin 泛型中型別投射

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關鍵字來投射一個型別