Scala 与 Java 对象的重写方法互操作
Scala interop with Java overriding method with Object
我有这个Java界面
public interface IFoo {
List<Map<String, Object>> getMaps() throws Exception;
}
我怎样才能重写这个方法?我试过了:
import scala.collection.JavaConverters._
class Foo extends IFoo{
override def getMaps: util.List[util.Map[String,AnyRef]] = {
List(Map("A" -> "B")).asJava
}
}
但是我遇到了这个编译错误
overriding method getMaps in trait IFoo of type
()java.util.List[java.util.Map[String,Object]]; [ERROR] method
getMaps has incompatible type
我可以做类似的事情:
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 ?
我无法重现您的 overriding incompatible type
错误。但是我在方法中得到了 type mismatch
,这个问题在这个答案中得到了解决。
class Foo extends IFoo{
override def getMaps: util.List[util.Map[String,AnyRef]] = {
List(Map("A" -> "B").mapValues(x => x: AnyRef).asJava).asJava
}
}
您还需要将 Map
转换为 Java Map
,并且有更好的方法来提供值类型:
List(Map[String, AnyRef]("A" -> "B").asJava).asJava
我有这个Java界面
public interface IFoo {
List<Map<String, Object>> getMaps() throws Exception;
}
我怎样才能重写这个方法?我试过了:
import scala.collection.JavaConverters._
class Foo extends IFoo{
override def getMaps: util.List[util.Map[String,AnyRef]] = {
List(Map("A" -> "B")).asJava
}
}
但是我遇到了这个编译错误
overriding method getMaps in trait IFoo of type ()java.util.List[java.util.Map[String,Object]]; [ERROR] method getMaps has incompatible type
我可以做类似的事情:
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 ?
我无法重现您的 overriding incompatible type
错误。但是我在方法中得到了 type mismatch
,这个问题在这个答案中得到了解决。
class Foo extends IFoo{
override def getMaps: util.List[util.Map[String,AnyRef]] = {
List(Map("A" -> "B").mapValues(x => x: AnyRef).asJava).asJava
}
}
您还需要将 Map
转换为 Java Map
,并且有更好的方法来提供值类型:
List(Map[String, AnyRef]("A" -> "B").asJava).asJava