0

I have a class defined in java

public class A {
    List<Group> javaMethod() {
    }
}

and a class in Scala

public class S extends A {
    override javaMethod: List[Group] {

    }
}

However, I get an error saying method javaMethod has incompatible type, I'm assuming because of the List that gets returned in the method when it gets overwritten, is of type scala.immutable.List, and the one that is required for the javaMethod is java.util.List.

I don't have access to class A, so I can't change the signature of the function. How can I return a scala List where I'm overriding the method, without getting a type error?

EDIT: This will get my list from Java to Scala, but I'm wanting to convert the Java list to the Scala list.

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
asList(ListBuffer(List(1,2,3): _*))
val x: java.util.List[Int] = ListBuffer(List(1,2,3): _*)
Rafa
  • 3,219
  • 4
  • 38
  • 70
  • 1
    I don't think you can. The return value *must* be a (subclass of) `List`. To get an entirely different return type, you must create a different method, e.g. `javaMethod2`, and assuming your implementation actually creates a `List[Group]`, you would then still override `javaMethod`, but with return type `List`, having it simply call `javaMethod2` and convert `List[Group]` to `List`. – Andreas Jan 26 '17 at 22:27
  • 1
    Possible duplicate of [How to convert a scala.List to a java.util.List?](http://stackoverflow.com/questions/2429944/how-to-convert-a-scala-list-to-a-java-util-list) – shmosel Jan 26 '17 at 22:29
  • @shmosel I want to do the reverse way – Rafa Jan 26 '17 at 22:55
  • What is stopping you from using `java.util.List[Group]`? – OneCricketeer Jan 26 '17 at 23:23
  • the whole rest of the codebase that depends on that value – Rafa Jan 27 '17 at 00:49
  • @ralphie9224 You have a scala list and your interface requires you to produce a java list. There's no way to change that without redefining `A`. Hence, the only solution is to convert your list to a java list. The reverse would accomplish nothing. – shmosel Jan 27 '17 at 00:56

0 Answers0