Skip to content

Instantly share code, notes, and snippets.

@JoshRosen
Created July 19, 2012 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshRosen/3145737 to your computer and use it in GitHub Desktop.
Save JoshRosen/3145737 to your computer and use it in GitHub Desktop.
Wildcard upper type bounds in Scala and Java
JavaTest.java:11: g(java.lang.Class<? extends java.lang.Iterable<?>>) in ScalaTest cannot be applied to (java.lang.Class<java.util.ArrayList>)
ScalaTest.g(ArrayList.class);
^
JavaTest.java:15: <T>f(java.lang.Class<T>) in ScalaTest cannot be applied to (java.lang.Class<java.lang.Object>)
ScalaTest.f(Object.class);
^
JavaTest.java:16: g(java.lang.Class<? extends java.lang.Iterable<?>>) in ScalaTest cannot be applied to (java.lang.Class<java.lang.Object>)
ScalaTest.g(Object.class);
^
JavaTest.java:17: <T>f(java.lang.Class<T>) in JavaTest cannot be applied to (java.lang.Class<java.lang.Object>)
JavaTest.f(Object.class);
^
JavaTest.java:18: g(java.lang.Class<? extends java.lang.Iterable>) in JavaTest cannot be applied to (java.lang.Class<java.lang.Object>)
JavaTest.g(Object.class);
^
5 errors
import java.util.ArrayList;
import java.lang.Iterable;
public class JavaTest {
public static <T extends Iterable> void f(Class<T> x) {}
public static void g(Class<? extends Iterable> x) {}
public static void main(String[] args) {
// Should compile:
ScalaTest.f(ArrayList.class);
ScalaTest.g(ArrayList.class);
JavaTest.f(ArrayList.class);
JavaTest.g(ArrayList.class);
// Should fail:
ScalaTest.f(Object.class);
ScalaTest.g(Object.class);
JavaTest.f(Object.class);
JavaTest.g(Object.class);
}
}
import java.lang.Iterable
object ScalaTest {
def f[T <: Iterable[_]](x : Class[T]) {}
def g(x : Class[_ <: Iterable[_]]) {}
}
@JoshRosen
Copy link
Author

The Java type Class<? extends Iterable> is not equivalent to Class<? extends Iterable<?>>. The Scala type Class[_ <: Iterable[_] appears to be equivalent to Class<? extends Iterable<?>>, but the Java type Class<? extends Iterable> appears to have no direct Scala equivalent.

The same compilation error occurs if the Java method JavaTest.g() is redefined as

public static void g(Class<? extends Iterable<?>> x) {}

so this is not a Scala issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment