美文网首页
google kotlin 训练营-泛型

google kotlin 训练营-泛型

作者: wwq2020 | 来源:发表于2020-07-22 15:36 被阅读0次

    原文

    class MyList<T> {
    fun get(pos: Int): T {
    TODO("implement")
    }
    fun addItem(item: T) {}
    }
    

    默认 T 可为 null
    相当于

    class MyList<T:Any?> {
    fun get(pos: Int): T {
    TODO("implement")
    }
    fun addItem(item: T) {}
    }
    

    如果想不为null,则

    class MyList<T:Any> {
    fun get(pos: Int): T {
    TODO("implement")
    }
    fun addItem(item: T) {}
    }
    

    check
    如果waterSupply.needsProcessing为true,则抛出异常

    class Aquarium<T: WaterSupply>(val waterSupply: T) {
    fun addWater() {
    check(!waterSupply.needsProcessing) { "water supply needs processing first" }
    println("adding water from \$waterSupply")
    }  
    }
    

    泛型函数

    fun <T: WaterSupply> isWaterClean(aquarium: Aquarium<T>) {
       println("aquarium water is clean: ${!aquarium.waterSupply.needsProcessing}")
    }
    

    泛型方法

    inline fun <reified R: WaterSupply> hasWaterSupplyOfType() = waterSupply is R
    

    扩展函数

    inline fun <reified R: WaterSupply> Aquarium<*>.hasWaterSupplyOfType() = waterSupply is R
    
    
    inline fun <reified R: WaterSupply> Aquarium<*>.hasWaterSupplyOfType() = waterSupply is R
    

    相关文章

      网友评论

          本文标题:google kotlin 训练营-泛型

          本文链接:https://www.haomeiwen.com/subject/yvqtlktx.html