Suppose we have the following Java interface:
// Java
public interface Foo {
<T> T bar(Class<T> c);
}
How should I extend it in Scala? Writing
// Scala
class FooString extends Foo {
override def bar(c: Class[String]): String = "hello, world";
}
will cause the compiler to throw "class FooString needs to be abstract, since method bar in trait Foo of type [T]
(Class[T])T is not defined."
Thanks in advance!
Update: The ugly truth is: I've misunderstood generics in Java.
In any case, the solutions to my woes are shown in both Nicolas' and Walter's answers, although I prefer Walter's answer better 'cos it's less verbose.
It does not work because you do not implements the interface properly. The siganture of your method n scala must be:
def bar[T](c:Class[T]):T
You can fix the behaviour for String only if you want ton implements Foo.
Third try, according to our discussion:
def bar[T](c:Class[T]):T = {
// Some stuff
val o:Any = myUntypedFunction(env)
c.cast(o)
}
According to the context the myUntypedFunction will create an object, and then you use the class parameter to cast your result and obtain a T object. Once again: this behavior is the same in java and in scala.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With