J.t*_*.ty 5 java generics kotlin
这是我的代码
[Kotlin]
internal abstract class Parent<out T, in V> constructor(
tList: List<T>,
vList: List<V>
) {
abstract fun get(): List<T>
abstract fun set(v: List<V>)
}
Run Code Online (Sandbox Code Playgroud)
[Java] - 它继承了kotlin类Parent.
final class Child extends Parent<Number, String> {
public Child(
@NotNull List<? extends Number> tList,
@NotNull List<? extends String> vList) {
super(tList, vList);
}
@NotNull @Override
public List<Number> get() {
return null;
}
@Override
public void set(@NotNull List<? extends String> v) {}
}
Run Code Online (Sandbox Code Playgroud)
Parent类有Generics,叫做T(out),V(in),
所以我认为..
类Child的构造函数应该是..
public Child(
@NotNull List<? extends Number> tList,
@NotNull List<? super String> vList) {
super(tList, vList);
}
Run Code Online (Sandbox Code Playgroud)
即第二个参数vList应该是
List<? super String>
Run Code Online (Sandbox Code Playgroud)
因为父母的通用的V是'in'但它是..
List<? extends String>
Run Code Online (Sandbox Code Playgroud)
有没有人可以解释这个?帮我!
[编辑] ...
public Child(
@NotNull List<Number> tList,
@NotNull List<String> vList) {
super(tList, vList);
}
Run Code Online (Sandbox Code Playgroud)
这可能..我的问题中的代码只是从IDE生成的代码..
小智 2
在 Kotlin 中,接口List
是不可变的,这意味着它是只读的。
这是它的签名:
public interface List<out E> : Collection<E>
Run Code Online (Sandbox Code Playgroud)
所以你的构造函数实际上看起来像这样:
internal abstract class Parent<out T, in V> constructor(
tList: List<out T>,
vList: List<out V>
)
Run Code Online (Sandbox Code Playgroud)
如果您想将值放入vList
(您通过使用声明in
),则必须使用 MutableList 接口:
internal abstract class Parent<T, V> constructor(
tList: List<T>,
vList: MutableList<in V>
)
Run Code Online (Sandbox Code Playgroud)