7

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?

8
  • I read through and tried to recreate that solution. Unfortunately I cannot import any of the Scala classes in my Java class, which I presume is something weird on my end. Sigh. Commented Jul 7, 2016 at 1:01
  • Sorry, but why can't you import any scala classes on your end? Even scala.collection.immutable.Map? Commented Jul 7, 2016 at 1:03
  • I wish I knew. But yeah, even scala.collection.immutable.Map will not import. Commented Jul 7, 2016 at 1:04
  • I suppose this is a problem with Eclipse. Try to reimport the project and see if it works. Commented Jul 7, 2016 at 1:05
  • No that is not a very good idea, using Scala code from Java is just horrible... the Scala compiler generates weird names that are not human-readable. Using Java from Scala is much easier because the Java compiler is way simpler and the naming rules of methods and classes much more restrictive. Simply use JavaConversions. Commented Jul 7, 2016 at 1:08

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

2 Comments

because Java map does not have the "asScala".
@AminHeydariAlashti that's the reason import scala.collection.JavaConverters._ was used.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.