Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend Java interface containing generic methods in Scala?

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.

like image 307
shaolang Avatar asked Dec 30 '22 14:12

shaolang


1 Answers

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.

like image 59
Nicolas Avatar answered Jan 13 '23 14:01

Nicolas