Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Java map into a Scala immutable map in Java code [duplicate]

Tags:

scala

I have a Java class that needs to stay in Java for a variety of reasons. It is calling a method on a class implemented with a Scala trait and a Scala implementation that needs a Scala immutable map. Yes, I have seen how to use implicit and explicit code if I have the Java Map and I am doing the converting in Scala code, but I am trying to do the conversion from Java code and have seen nothing like that on Stack Overflow.

I am using Eclipse and the project has the Scala nature added to it. I tried importing scala.collection.JavaConverters, and Eclipse just gave me an error saying it couldn't find the class even though I can see the class when I open up the scala-library in the Scala Library container. I am using Scala 2.11.8

How can I write explicit code that converts the Java Map into the Scala Map in Java code?

like image 800
Keith Avatar asked Jul 07 '16 00:07

Keith


People also ask

How do I convert a mutable Map to immutable Map in Scala?

You can use myMap. toMap to convert an a mutable map into immutable in Scala 2.8 and later versions.

Is Map immutable in Scala?

Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.

What is difference between Map and HashMap in Scala?

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same.


1 Answers

Why not simply use toMap.

Something Like :

import scala.collection.JavaConverters._

// asScala creates mutable Scala Map
// toMap after asScala creates immutable Map
val scalaImmutableMap = javaMap.asScala.toMap
like image 184
Abhishek Sengupta Avatar answered Sep 19 '22 15:09

Abhishek Sengupta