Search code examples
scalayamlsnakeyaml

Why my simple scala file use snakeyaml can't dump a map as YAML to a file?


I have this simple scala file use snakeyaml:

object Main extends App {
var a=Map[String,Object]()
a+=("a"->"b")
println(a("a"))

val yaml=new Yaml()
val fileWriter = new FileWriter("d:\\src\\scala\\yaml.txt")
yaml.dump(a,fileWriter)}

I only got this in yaml.txt:

!!scala.collection.immutable.Map$Map1 {}

Why isn't this {a: b}?


Solution

  • I suspect this happens because SnakeYAML is a Java library and it is not aware of Scala-specific collections. So to dump your Scala-Map with the library, you should convert it to a Java-Map first. Probably the code like this will help:

    import scala.collection.JavaConverters._
    
    ...
    
    yaml.dump(a.asJava,fileWriter)
    

    If you want to dump a lot of different Scala collections, you might consider implementing a custom Representers and Constructors for them.