Monday, November 23, 2009

Consice Java Maps in Scala

This post is a follow up to my previous post on using Closure Templates in Scala.

One of the things that bugged me in the Scala example was how verbose it was compared to the Groovy version. So I had an idea - use YAML and the snakeyaml library to generate a Java Map with my data. While it's still a couple lines longer than the Groovy version, it's a lot simpler than the Scala original.

The biggest change is this:

val y = """widget: {
name: Widget Name,
display: {
width: 240,
height: 320
}
}"""

val yaml = new Yaml()
val map = yaml.load(y).asInstanceOf[java.util.Map[String, _]]


Scala Source Code

3 comments:

Andrey Somov said...

Hi,
how do you find SnakeYAML ? Is it difficult to use ?

Scot McSweeney-Roberts said...

I found SnakeYAML fairly easy to use, especially once I found the JavaDoc.

I think the hardest part was remembering how to type cast in Scala :-)

Jan said...

What about something like:

val $ = Map

val map = $(
"widget" -> $(
"name" -> "Scala Test",
"display" -> $(
"width"-> 240,
"height" -> 320)))