Home > Articles

This chapter is from the book

4.6 Interoperating with Java

If you get a Java map from calling a Java method, you may want to convert it to a Scala map so that you can use the pleasant Scala map API.

Simply add an import statement:

import scala.jdk.CollectionConverters.*

Then use the asScala method to turn the Java map into a Scala map:

val ids = java.time.ZoneId.SHORT_IDS.asScala
  // Yields a scala.collection.mutable.Map[String, String]

In addition, you can get a conversion from java.util.Properties to a Map[String, String]:

val props = System.getProperties.asScala
  // Yields a Map[String, String], not a Map[Object, Object]

Conversely, to pass a Scala map to a method that expects a Java map, provide the opposite conversion. For example:

import java.awt.font.TextAttribute.* // Import keys for map below
val attrs = Map(FAMILY -> "Serif", SIZE -> 12) // A Scala map
val font = java.awt.Font(attrs.asJava) // Expects a Java map

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.