Scala type inference failure on "? extends" in Java code
Posted
by oxbow_lakes
on Stack Overflow
See other posts from Stack Overflow
or by oxbow_lakes
Published on 2010-03-22T10:34:50Z
Indexed on
2010/03/22
12:11 UTC
Read the original article
Hit count: 277
I have the following simple Java code:
package testj;
import java.util.*;
public class Query<T> {
private static List<Object> l = Arrays.<Object>asList(1, "Hello", 3.0);
private final Class<? extends T> clazz;
public static Query<Object> newQuery() { return new Query<Object>(Object.class); }
public Query(Class<? extends T> clazz) { this.clazz = clazz; }
public <S extends T> Query<S> refine(Class<? extends S> clazz) {
return new Query<S>(clazz);
}
public List<T> run() {
List<T> r = new LinkedList<T>();
for (Object o : l) {
if (clazz.isInstance(o)) r.add(clazz.cast(o));
}
return r;
}
}
I can call this from Java as follows:
Query<String> sq = Query.newQuery().refine(String.class); //NOTE NO <String>
But if I try and do the same from Scala:
val sq = Query.newQuery().refine(classOf[String])
I get the following error:
error: type mismatch
found :lang.this.class[scala.this.Predef.String]
required: lang.this.class[?0] forSome{ type ?0 <: ? }
val sq = Query.newQuery().refine(classOf[String])
This is only fixed by the insertion of the correct type parameter!
val sq = Query.newQuery().refine[String](classOf[String])
Why can't scala infer this from my argument? Note I am using Scala 2.7
© Stack Overflow or respective owner