kotlin 泛型攻略

基础用法

  • 在 Kotlin 中使用 :代替 extends 对泛型的的类型上界进行约束。
fun  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中的 &的 是 where关键字
//java实现
class ClassA { }
interface InterfaceB { }
public class MyClass {
    Class variable;
}

//kotlin 实现
open class ClassA
interface InterfaceB
interface InterfaceC
class Myclass where T : ClassA, T : InterfaceB ,T:InterfaceC
  • in和out修饰符分别表示 该参数只能做入参或者只能做出参(返回类型)
fun main() {
    val list1:MutableList = mutableListOf()
    list1.add("hello")
    list1.add("world")
    val list2:MutableList = mutableListOf()
    list2.add("hello")  // compile error
    list2.add("world")  // compile error
    val list3:MutableList = mutableListOf()
    list3.add("hello")
    list3.add("world")
    lateinit var list4:MutableList
    list4 = list3;     // compile error
}
  • <*>星号投影表示不确定类型类似于java无类型通配符 因为类型不确定 所以星号投影只能读取不能写入

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

你可能感兴趣的:(kotlin 泛型攻略)