Kotlin - "in"关键字 - 用于什么?

标签 kotlin

我试图了解何时在泛型中使用“in”关键字而不是“out”关键字(它允许分配给子类)。

我实际上正在关注这个tutorial如果重要的话。

假设我们有以下类定义:

class ParameterizedConsumer<in T> {
    fun toString(value: T): String {
        return value.toString()
    }
}

由于不保证 value 是 String ,这甚至如何编译?这是 in 关键字的作用吗?它告诉类(class)有保证该类型不会是任何其他子类?我只是不清楚它的用例,你能帮忙吗?

该教程说我将能够调用以下内容,但我不知道它发生了什么变化:
 val parameterizedConsumer = ParameterizedConsumer<Number>()

val ref: ParameterizedConsumer<Double> = parameterizedConsumer

assertTrue(ref is ParameterizedConsumer<Double>)

更新:我现在明白了。 Out 意味着你可以在生产时沮丧。而“In”表示分配时可以向下转换。

所以在java中这是不允许的:
// Java
void demo(Source<String> strs) {
  Source<Object> objects = strs; // !!! Not allowed in Java
  // ...
}

但是在 kotlin 中,我们可以解决这个问题,如果我们使用“out”关键字,我们可以将其分配给向下转换的类(子类)。同样,使用“in”,我们可以将子类传入类内部以供使用,但不能向外使用。

最佳答案

it tells the class that there is a guarantee the type wont be any other subclass ? I am just not clear on the usecase for it, can you help ?



假设您有一个函数想要将一些项目添加到您提供的列表中。项目类型为 Int .

问题:这个函数可以接受什么样的列表?

答:MutableList<Int> , MutableList<Number> , MutableList<Any> .或者,简而言之,MutableList<in Int> .

本着同样的精神,让我们解释一下 out投影。

假设您有一个函数想要从您提供的列表中获取一些元素。项目类型为 Future .

问题:这个函数可以接受什么样的列表?

答:List<Future> , List<RunnableFuture> , List<ScheduledFuture> ... 或者,简而言之,List<out Future> .

关于Kotlin - "in"关键字 - 用于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48258135/

相关文章:

kotlin - 在比较中忽略三元组的组成部分

android - 错误 : Entity class must be annotated with @Entity

由于使用 Jetpack Workflow 缺少 bool 资源值,Android 资源链接失败

java - Android kotlin/java - 注销 : clear shared preferences and stop all processes in background

Java 到 Kotlin_Gson.Json 转换错误

java - 如何在每次订阅可观察值时运行函数

用于 fragment 中状态流的 Android 通用函数

android - 带有 TabLayout 的 ViewPager2 未导航到正确的选项卡

kotlin - 在 kotlinc 的 jar 输出中包含反射库

android - 如何使用 Kotlin 更改 android 中的字体?