18
votes

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

1
Has this question been answered or is it still open?James Iry
I hadn't noticed your answer as I went on holiday shortly after this. Sorry. I'm pretty sure that I had read that there were "no wildcards in Scala". Was this ever the case? I assume it's not now...oxbow_lakes

1 Answers

44
votes

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.