我试图了解何时在泛型中使用“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/