-1

Totally new to scala so any help is appreciated. I'm trying to pass objects from python to scala via the JVM, so I need a function that takes a java map as an input and returns a scala map as output.

I'm not really sure yet if I want the map to be mutable or immutable, but I've played around with using .asScala.toMap to make it immutable, but that threw an error. I think the issues is with the syntax of my function?


private object PythonUtils {

  def toScalaMap[K, V](jm: java.util.Map[K, V]): Map[K, V] = {
    jm.asScala
  }

}

From what I've got so far, the function does a type check on the parameters and then takes java map and converts it to scala. However, when I compile this I'm getting a type mismatch error found: scala.collection.mutable.Map[K,V] required java.util.Map[K,V] Any assistance is greatly appreciated!

Molly
  • 49
  • 4

1 Answers1

1

Try

import scala.collection.JavaConverters._
import scala.collection.mutable

def toScalaMutableMap[K, V](jm: java.util.Map[K, V]): mutable.Map[K, V] = {
  jm.asScala
}

def toScalaImmutableMap[K, V](jm: java.util.Map[K, V]): Map[K, V] = {
  jm.asScala.toMap
}

libraryDependencies += "org.scala-lang.modules" %% "scala-java8-compat" % "0.9.0"

Convert Java Map to Scala Map

Converting mutable to immutable map

However, when I compile this I'm getting a type mismatch error found: scala.collection.mutable.Map[K,V] required java.util.Map[K,V]

Look what line produces this error.

Maybe you have import java.util.Map. Then Map refers to java.util.Map. If you remove this import then Map will refer to scala.Predef.Map aka scala.immutable.Map.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66