当前位置:网站首页>Use of out covariance and in inversion in kotlin

Use of out covariance and in inversion in kotlin

2022-07-07 08:14:00 yu-Knight

//in T out T  Specify the relationship at the declaration   Declared generic   This is a Java No function 

// Whole  SetClass  All the members inside   Generics related , It can only be modified but not read 
class SetClass<in T> {
    fun set1(item: T) {
        println("set1  Required item:$item")
    }

    fun set2(item: T) {
        println("set2  Required item:$item")
    }
}

// Whole  getClass  All the members inside   Generics related , Read only, not modify 
class GetClass<out T>(item: T) {
    val item: T = item
    fun get1(): T {
        return item
    }

    fun get2(): T {
        return item
    }
}

fun main(args: Array<String>) {
    // Inversion  in T SetClass  It can only be modified , The outside world cannot read 
    val p1 = SetClass<String>()
    p1.set1("yuknight") //set1  Required item:yuknight
    p1.set2("kotlin") //set2  Required item:kotlin
    // Covariance  out T GetClass  Can only read , The outside world can't modify 
    val p2 = GetClass("yuknight")
    println(p2.get1()) //yuknight
}

原网站

版权声明
本文为[yu-Knight]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130641028667.html