Could the following Java code:
public <T extends Enum<T>> T foo(Class<T> clazz) {
  return clazz.getEnumConstants()[0];
}
public void bar(Class<?> clazz) {
    if (Enum.class.isAssignableFrom(clazz)) {
        System.out.println(foo(clazz.asSubclass(Enum.class)));
    }
}
bar(MyEnum.class) // will print first value of MyEnum
bar(String.class) // won't print anything
be translated to Scala:
bar[MyEnum]()
bar[String]()
Enum is just an example of a class that follows the T extends Wrapper[T] pattern, and foo could have simply returned the name of the class (or perform any other kind of logic which requires reflective data that is only available in my "Wrapper" class).
I tried to make it work in Scala with TypeTag but failed; I got all sort of compilation errors, such as this: inferred type arguments [?0] do not conform to method foo's type parameter bounds [E <: Enum[E]]
Aucun commentaire:
Enregistrer un commentaire