In Programming in Scala, the following example is given to show how to reference a Java class with wildcards. The method javaSet2ScalaSet
takes a type T. Typically, you can always explicitly supply a parameterized type. But in this case where (new Wild).contents
is existential, a normal type parameter is not acceptable.
The compiler is able to perform some magic and infer an appropriate parameter when javaSet2ScalaSet
is called without a type parameter. Viewing what the compiler supplies with scalac –Xprint:typer shows that it assigns a value of ?0 for T. This can’t be provided manually.
Is this a special case that only works for an inferred type, or is there some way to explicitly supply the type?
// This is a Java class with wildcards
public class Wild {
Collection<?> contents() {
Collection<String> stuff = new Vector<String>();
stuff.add("a");
stuff.add("b");
stuff.add("see");
return stuff;
}
}
import scala.collection.mutable.Set
import java.util.Collection
abstract class SetAndType {
type Elem
val set: Set[Elem]
}
def javaSet2ScalaSet[T](jset: Collection[T]): SetAndType = {
val sset = Set.empty[T] // now T can be named!
val iter = jset.iterator
while (iter.hasNext)
sset += iter.next()
return new SetAndType {
type Elem = T
val set = sset
}
}
val setAndType = javaSet2ScalaSet((new Wild).contents)
javaSet2ScalaSet[T forSome {type T}]
(which is the same asjavaSet2ScalaSet[_]
). Is that what you mean? – Alexey RomanovjavaSet2ScalaSet[T forSome {type T}]
. The compiler complains with unbound wildcard type. Same withjavaSet2ScalaSet[_])
. – ToddLC