什么是 kotlin 中的 out 关键字 [英] What is out keyword in kotlin

查看:38
本文介绍了什么是 kotlin 中的 out 关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解,也找不到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可以安全地成为C超类型.

when a type parameter T of a class C is declared out, C<Base> can safely be a supertype of C<Derived>.

这与in形成对比,例如

Comparable<in T>

你可以这样做:

fun foo(numberComparable: Comparable<Number>) {
  val doubleComparable: Comparable<Double> = numberComparable
  // ...
}

这意味着 T逆变:

C类的类型参数T被声明in时,C可以安全地成为C超类型.

when a type parameter T of a class C is declared in, C<Derived> can safely be a supertype of C<Base>.

另一种记忆方式:

消费者输入,生产者输出.

参见 Kotlin 泛型差异

-----------------于 2019 年 1 月 4 日更新-----------------

对于Consumer in, Producer out",我们只从Producer读取——调用方法得到T类型的结果;并且只写入消费者 - 通过传入类型 T 的参数调用方法.

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的例子中,很明显我们可以这样做:

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 时提供 List 是安全的,因此 List 是超类型List,反之则不然.

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 的示例中:

val double: Double = 1.0
doubleComparable.compareTo(double)
numberComparable.compareTo(double)

所以在需要 Comparable 时提供 Comparable 是安全的,因此 Comparable 是超类型Comparable,反之则不然.

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 中的 out 关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆