Generic wildcards in variable declarations in Scala

oxbow_lakes picture oxbow_lakes · Mar 19, 2009 · Viewed 13.7k times · Source

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

Answer

James Iry picture James Iry · Mar 23, 2009

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.