views:

1263

answers:

2

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

A: 

I'm not sure at all I understand your question (probably not enough coffee on my part) but it sounds like you're asking about generic classes. If that's not it, drop a comment or add more information to your question & I'll check back later & edit my answer.

MarkusQ
I think I understand a bit more about it now; the difference between scala.List and scala.collection.Buffer being the List is covariant in its type whilst Buffer is not. In Java, generics are *always* covariant in T
oxbow_lakes
+6  A: 

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.

James Iry