Scala中变量声明中的通用通配符 [英] Generic wildcards in variable declarations in Scala

查看:116
本文介绍了Scala中变量声明中的通用通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我可能会这样做:

  class MyClass {
private List< ;?扩展MyInterface>列表;

public void setList(List< MyImpl> l){list = 1; }





假定( MyImpl实现了MyInterface )当然。



Scala 中使用 Buffer

  import java.lang.reflect._ 
import scala.collection .mutable._

class ScalaClass {
val list:Buffer [MyInterface] = null
$ b def setList(l:Buffer [MyImpl])= {




这个(当然)不会't编译 - 但我该如何声明 list 变量?



修改;我增加了一点。这种区别显然是与Java中的泛型在T中永不共变的事实有关,而在Scala中它们可以是协变或不变的。例如,Scala类 List 在T中是协变的(并且必然是不可变的)。因此,下面的将会被编译



pre $ class $ ScaClass {
val list:List [MyInterface ] = null
$ b $ def setList(l:List [MyImpl])= {
list = l
}
}


我还在努力解决编译错误:





例如;这个编译器错误发生在类声明中:

  class Wibble [+ T] {
var some:T = _ //编译器错误!
}

我要问一个单独的问题...

解决方案

直接模拟到

  import java.util.List的; 
列表< ;?扩展MyInterface>列表;



  import java.util.List 
var list:List [_< ;: MyInterface] = _;

与缓冲区相同处理

你在Java类型参数中做出的评论总是不变的,而不是协变的。

In Java I might do this:

class MyClass {
    private List<? extends MyInterface> list;

    public void setList(List<MyImpl> l) { list = l; }
}

...assuming that (MyImpl implements MyInterface) of course.

What is the analog for this in Scala, when using a 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 list variable in such a way that it does?

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 List is covariant in T (and necessarily immutable). Therefore the following will compile:

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 ...

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...

解决方案

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.

这篇关于Scala中变量声明中的通用通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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