I have an issue with the following hierarchy in scala:
class ScalaGenericTest {
def getValue[A, B <: Abstract[A]](clazz: B): A = clazz.a
def call: String = {
val sub: Subclass = new Subclass
getValue(sub)
}
}
class Subclass extends Abstract[String] {
def a: String = "STRING"
}
abstract class Abstract[A] {
def a: A
}
The compiler doesn't seem to be able to bind the generic parameter A in the call to the getValue function -- I think it should be able to infer this from the definition of Subclass. The compile error is as follows:
inferred type arguments [Nothing,Subclass] do not conform to method getValue's type parameter bounds [A,B <: Abstract[A]]
It works if I explicitly pass the generic type arguments to the method, i.e. getValue[String,Subclass](sub)
but surely the compiler should be able to infer this?
The same hierarchy works fine in Java:
public class JavaGenericTest {
public <T,U extends Abstract<T>> T getValue(U subclass) {
return subclass.getT();
}
public String call(){
Subclass sub = new Subclass();
return getValue(sub);
}
private static class Subclass extends Abstract<String> {
String getT(){
return "STRING";
}
}
private static abstract class Abstract<T> {
abstract T getT();
}
}
I'm pretty new to Scala so there's probably some subtlety that I'm missing.
Thanks in advance for any help!