4

I have a Java method where the signature looks like:

public Map<String, ?> getData() {
    return data;
}

I am trying to take this return value as a parameter to a Scala method:

import java.util.{Map => jMap}

def myMethod(m: jMap[String, Any]): Unit = {
  // do stuff
}

// myMethod(foo.getData())

With this, the compiler will complain:

 found   : java.util.Map[String,?0] where type ?0
 required: java.util.Map[String,Any]

What is ?, and what is its Scala equivalent?

When I try:

def myMethod(m: jMap[String, ?]): Unit = {
  // do stuff
}

that errors with:

not found: type ?

Info:

Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z)
Maven home: /usr/share/maven
Java version: 1.8.0_152, vendor: Oracle Corporation
Java home: /usr/java/jdk1.8.0_152/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.19.76-linuxkit", arch: "amd64", family: "unix"
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235

1 Answers1

2

While maybe not the canonical or most efficient solution, I ended up converting the Java map to a Scala Map, coupled with _ in place of Any. Note that .asScala will produce a mutable map by default.

import scala.collection.mutable
import scala.jdk.CollectionConverters._

def myMethod(m: mutable.Map[String, _]): Unit = {
// ...

myMethod(obj.getData().asScala)

Note: collection.JavaConverters._ is deprecated in favor of scala.jdk.CollectionConverters._ since 2.13.1. [source]

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • 2
    IMO it is both canonical and efficient as they are just wrappers that forward to underlying collection. In Scala 2.13 use `import scala.jdk.CollectionConverters._`. – Mario Galic Mar 19 '20 at 20:37