Scala type inference failure on "? extends" in Java code
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 tr开发者_开发问答y 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
The inference works against Scala 2.8.0.Beta1.
For earlier versions, it works if you change:
public <S extends T> Query<S> refine(Class<? extends S> clazz)
to:
public <S extends T> Query<S> refine(Class<S> clazz)
scalac -print
suggests that the interpretation of the Java signatures hasn't changed across Scala releases. So the difference is probably in the typer/inferencer itself.
Scala 2.7.5
Original
def refine[S >: _root_.scala.Nothing <: T](clazz: Class[_$1] forSome {
type _$1 >: Nothing <: S
}): Query[S] = _;
Modified
def refine[S >: _root_.scala.Nothing <: T](clazz: Class[S]): Query[S] = _;
Scala 2.8.0.Beta1
Original
def refine[S >: scala.Nothing <: T](clazz: Class[_$1] forSome {
type _$1 >: Nothing <: S
} = _): Query[S] = _;
Modified
def refine[S >: scala.Nothing <: T](clazz: Class[S] = _): Query[S] = _;
精彩评论