Kotlin中的“out”关键字是什么?


Out”关键字广泛使用于 Kotlin 泛型。它的签名如下所示 −

List<out T>

当类 C 的类型参数 T 被声明为 out,则 C 可以安全地作为 C<Derived> 的超类型。这意味着,一个Number 类型的列表可以包含double,integer 类型的列表。

示例

以下示例演示了如何在 Kotlin 中使用“out”关键字 −

fun main(args: Array<String>) {
   var objet1 = genericsExample<Int>(10)
   var objet2 = genericsExample<Double>(10.0)
}

// As generic type is declared as "out",
// we can pass Int and Double also.

class genericsExample<out T>(input:Any?) {
   init {
      println("I am getting called with the value "+input)
   }
}

输出

它将产生以下输出

I am getting called with the value 10
I am getting called with the value 10.0

更新于: 2021-11-23

939 浏览

启动你的职业

完成课程获得认证

开始学习
广告
© . All rights reserved.