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?

Keith
  • 337
  • 3
  • 12
  • 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. – Keith Jul 07 '16 at 01:01
  • Sorry, but why can't you import any scala classes on your end? Even `scala.collection.immutable.Map`? – marcospereira Jul 07 '16 at 01:03
  • I wish I knew. But yeah, even scala.collection.immutable.Map will not import. – Keith Jul 07 '16 at 01:04
  • I suppose this is a problem with Eclipse. Try to reimport the project and see if it works. – marcospereira Jul 07 '16 at 01: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`. – Dici Jul 07 '16 at 01:08
  • I agree, using Scala from Java is horrible. But it will sometimes be necessary and I ran into that time, which was fortunately just a small usage. But now that I see what interoperate is like, I am beginning to wonder if doing future work in Scala is a good idea if I want people to have a choice of using Java. Anyway, I got Eclipse sorted out. It was odd, containers in the .classpath file when flipped made it work. – Keith Jul 07 '16 at 01:14
  • BTW, my problem was solved by following a few threads. I apologize that a solution was out there, I tried searching and never found those discussions. – Keith Jul 07 '16 at 01:18
  • http://stackoverflow.com/questions/11903167/convert-java-util-hashmap-to-scala-collection-immutable-map-in-java/11903737#11903737 solves the problem in the more "modern" way. Which just misses a few $s. – Keith Jul 07 '16 at 01:20

1 Answers1

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
Abhishek Sengupta
  • 2,938
  • 1
  • 28
  • 35