Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

java - Generic wildcards in variable declarations in Scala

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...