Scala 变量声明中的通用通配符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/663032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generic wildcards in variable declarations in Scala
提问by oxbow_lakes
In Java I might do this:
在 Java 中,我可能会这样做:
class MyClass {
private List<? extends MyInterface> list;
public void setList(List<MyImpl> l) { list = l; }
}
...assuming that (MyImpl implements MyInterface) of course.
...MyImpl implements MyInterface当然,假设 ( ) 。
What is the analog for this in Scala, when using a Buffer?
当使用 a 时,Scala 中的this 的模拟是Buffer什么?
import java.lang.reflect._
import scala.collection.mutable._
class ScalaClass {
val list:Buffer[MyInterface] = null
def setList(l: Buffer[MyImpl]) = {
list = l
}
}
This (of course) doesn't compile - but how do I declare the listvariable in such a way that it does?
这(当然)不会编译 - 但是我如何list以这样的方式声明变量?
EDIT; I'm adding a bit more. The difference is obviously something to do with the fact that in Java, generics are never covariant in T, whereas in Scala they can be either covariant or not. For example, the Scala class Listis covariant in T (and necessarily immutable). Therefore the following will compile:
编辑; 我再补充一点。区别显然与以下事实有关:在 Java 中,泛型在 T中从不协变,而在 Scala 中,它们可以是协变的,也可以不是协变的。例如,Scala 类List在 T 中是协变的(并且必然是不可变的)。因此,以下将编译:
class ScalaClass {
val list:List[MyInterface] = null
def setList(l: List[MyImpl]) = {
list = l
}
}
I'm still struggling a bit with the compiler error:
我仍然在为编译器错误而苦苦挣扎:
Covariant type T occurs in contravariant position in ...
Covariant type T occurs in contravariant position in ...
For example; this compiler error occurs in the class declaration:
例如; 这个编译器错误发生在类声明中:
class Wibble[+T] {
var some: T = _ //COMPILER ERROR HERE!
}
I'm going to ask a separate question...
我要问一个单独的问题...
回答by James Iry
The direct analog to
直接模拟
import java.util.List;
List<? extends MyInterface> list;
is
是
import java.util.List
var list : List[_ <: MyInterface] = _;
Same deal with Buffer
与缓冲区相同的处理
To answer a comment you made earler, in Java type parameters are always invariant, not covariant.
为了回答您之前发表的评论,在 Java 中类型参数始终是不变的,而不是协变的。

