简体   繁体   English

Scala映射值扩展接口

[英]Scala map value extends interface

This method is in a Java library we are calling 该方法在我们正在调用的Java库中

   public void setNumbers(Map<Integer, ? extends COSObjectable> numbers) {
...
    }

I have a mixed Java/Scala project, I moved working code from a Java class into a Scala class and now I can't get this call to work from Scala. 我有一个Java / Scala混合项目,我将工作代码从Java类移到了Scala类,现在我无法从Scala调用此代码。 The best I've been able to get is 我所能得到的最好的是

  val numbers = new util.HashMap[Integer, _ <: COSObjectable ]
  node.setNumbers(numbers)

which is failing to compile with 无法编译

class type required but java.util.HashMap[Integer, _ <: org.apache.pdfbox.pdmodel.common.COSObjectable] found 类类型为必需,但是找到了java.util.HashMap [Integer,_ <:org.apache.pdfbox.pdmodel.common.COSObjectable]

The COSObjectable parameter of the map is a java interface 映射的COSObjectable参数是一个Java接口

public interface COSObjectable {
    COSBase getCOSObject();
}

I'm not sure Scala likes this syntax when used with an interface. 我不确定Scala与接口一起使用时是否喜欢这种语法。 It seems to be saying I can only do this with a class. 似乎是在说我只能在一堂课上做。

我想也许我只是太努力了,脱掉_ <:似乎有效

val numbers = new util.HashMap[Integer, COSObjectable ]

I was able to make it work with: 我能够使其与:

object Tes {
  case class RandomStuff()
  val numbers = new java.util.HashMap[Integer, _ <: RandomStuff ]
}

or 要么

  trait COSObjectable {
    def getCOSObject: Nothing
  }

  val numbers: Map[Integer, _ <: COSObjectable ] = Map.empty

When you instantiate a class you need to use a specific type, not a wildcard. 当实例化一个类时,您需要使用特定的类型,而不是通配符。 Just like in Java you cannot do new util.HashMap<Integer, ? extends COSObjectable> 就像在Java中一样,您不能执行new util.HashMap<Integer, ? extends COSObjectable> new util.HashMap<Integer, ? extends COSObjectable> you can do the equivalent new util.HashMap[Integer, _ <: COSObjectable] . new util.HashMap<Integer, ? extends COSObjectable>您可以执行等效的new util.HashMap[Integer, _ <: COSObjectable]

You need to specify the acutal type like new util.HashMap[Integer, COSObjectable] (or whatever subtype of COSObjectable you require). 您需要指定new util.HashMap[Integer, COSObjectable]类型,例如new util.HashMap[Integer, COSObjectable] (或所需的COSObjectable类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM