kotlin 泛型攻略

2021-02-04  本文已影响0人  忧郁的老王

基础用法

fun <T : Number> sum(vararg param: T) = param.sumByDouble { it.toDouble() }
fun main() {
    val result1 = sum(1,10,0.6)
    val result2 = sum(1,10,0.6,"kotlin") // compile error
}
//java实现
class ClassA { }
interface InterfaceB { }
public class MyClass<T extends ClassA & InterfaceB> {
    Class<T> variable;
}

//kotlin 实现
open class ClassA
interface InterfaceB
interface InterfaceC
class Myclass<T> where T : ClassA, T : InterfaceB ,T:InterfaceC
fun main() {
    val list1:MutableList<String> = mutableListOf()
    list1.add("hello")
    list1.add("world")
    val list2:MutableList<out String> = mutableListOf()
    list2.add("hello")  // compile error
    list2.add("world")  // compile error
    val list3:MutableList<in String> = mutableListOf()
    list3.add("hello")
    list3.add("world")
    lateinit var list4:MutableList<String>
    list4 = list3;     // compile error
}

    fun test(list:MutableList<*>) {
        list.add("s") // compile error
    }
上一篇 下一篇

猜你喜欢

热点阅读