什么是Kotlin关键字 [英] What is out keyword in kotlin
问题描述
我听不懂,在kotlin中找不到 out 关键字的含义.
I am not able to understand and I couldn't find the meaning of out keyword in kotlin.
您可以在此处查看示例:
You can check example here:
List<out T>
如果有人可以解释这个意思.会非常感激的.
If any one can explain the meaning of this. It would be really appreciated.
推荐答案
具有此签名:
List<out T>
您可以执行以下操作:
val doubleList: List<Double> = listOf(1.0, 2.0)
val numberList: List<Number> = doubleList
这意味着 T 是协变:
当将 C 类的类型参数 T 声明为 out 时, C< Base> 成为 C< Derived> 的超类型.
when a type parameter T of a class C is declared out, C<Base> can safely be a supertype of C<Derived>.
这与中的相反,例如
Comparable<in T>
您可以执行以下操作:
fun foo(numberComparable: Comparable<Number>) {
val doubleComparable: Comparable<Double> = numberComparable
// ...
}
这意味着 T 是相反的:
在中用声明了类 C 的类型参数 T 时, C< Derived> 成为 C< Base> 的超类型.
when a type parameter T of a class C is declared in, C<Derived> can safely be a supertype of C<Base>.
另一种记忆方式:
消费者输入,生产者输出.
请参见科特琳的仿制药差异
-----------------已于2019年1月4日更新-----------------
对于"消费端,生产者端",我们仅从生产者端读取-调用方法以获取类型T的结果;并且只能通过传入T类型的参数来写入Consumer-call方法.
For the "Consumer in, Producer out", we only read from Producer - call method to get result of type T; and only write to Consumer - call method by passing in parameter of type T.
在List<out T>
的示例中,很明显,我们可以这样做:
In the example for List<out T>
, it is obvious that we can do this:
val n1: Number = numberList[0]
val n2: Number = doubleList[0]
因此,在期望使用List<Number>
时提供List<Double>
是安全的,因此List<Number>
是List<Double>
的超类型,反之亦然.
So it is safe to provide List<Double>
when List<Number>
is expected, hence List<Number>
is super type of List<Double>
, but not vice versa.
在Comparable<in T>
的示例中:
val double: Double = 1.0
doubleComparable.compareTo(double)
numberComparable.compareTo(double)
因此,在期望使用Comparable<Double>
时提供Comparable<Number>
是安全的,因此Comparable<Double>
是Comparable<Number>
的超类型,反之亦然.
So it is safe to provide Comparable<Number>
when Comparable<Double>
is expected, hence Comparable<Double>
is super type of Comparable<Number>
, but not vice versa.
这篇关于什么是Kotlin关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!