0
votes

I have this Java interface

public interface IFoo {

    List<Map<String, Object>> getMaps() throws Exception;
}

how can I override this method ? i tried :

import scala.collection.JavaConverters._
class Foo extends IFoo{
 override def getMaps: util.List[util.Map[String,AnyRef]]  = {
    List(Map("A" -> "B")).asJava
  }
}

but I am getting this compilation error

overriding method getMaps in trait IFoo of type ()java.util.List[java.util.Map[String,Object]]; [ERROR] method getMaps has incompatible type

I can do something like :

import scala.collection.JavaConverters._
class Foo extends IFoo{
 override def getMaps: util.List[util.Map[String,AnyRef]]  = {
    List(Map("A" -> "B".asInstanceOf[AnyRef)).asJava
  }
}

But is it the correct way ?

2

2 Answers

1
votes

I could not reproduce your overriding incompatible type error. But I get type mismatch inside the method and that trouble is fixed in this answer.

class Foo extends IFoo{
  override def getMaps: util.List[util.Map[String,AnyRef]]  = {
    List(Map("A" -> "B").mapValues(x => x: AnyRef).asJava).asJava
  }
}
1
votes

You need to convert Map to a Java Map as well, and there is a better way to provide the value type:

List(Map[String, AnyRef]("A" -> "B").asJava).asJava