Iterate over fields in typesafe config

Egor Koshelko picture Egor Koshelko · Jul 11, 2013 · Viewed 21.3k times · Source

I have perks.conf:

autoshield {
    name="autoshield"
    price=2
    description="autoshield description"
}
immunity {
    name="immunity"
    price=2
    description="autoshield description"
}
premium {
    name="premium"
    price=2
    description="premium description"
}
starter {
    name="starter"
    price=2
    description="starter description"
}
jetpack {
    name="jetpack"
    price=2
    description="jetpack description"
}

And I want to iterate over perks in my application something like this:

val conf: Config = ConfigFactory.load("perks.conf")
val entries = conf.getEntries()
for (entry <- entries) yield {
  Perk(entry.getString("name"), entry.getInt("price"), entry.getString("description"))
}

But I can't find appropriate method which returns all entries from config. I tried config.root(), but it seems it returns all properties including system, akka and a lot of other properties.

Answer

Yuri Geinish picture Yuri Geinish · Feb 26, 2014

entrySet collapses the tree. If you want to iterate over immediate children only, use:

conf.getObject("perks").asScala.foreach({ case (k, v) => ... })

k will be "autoshield" and "immunity", but not "autoshield.name", "autoshield.price" etc.

This requires that you import scala.collection.JavaConverters._.