scalatypesafe

Iterate over fields in typesafe config


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.


Solution

  • For example you have the following code in your Settings.scala

    val conf = ConfigFactory.load("perks.conf")
    

    if you call entrySet on the root config (not conf.root(), but the root object of this config) it will returns many garbage, what you need to do is to place all your perks under some path in the perks.conf:

    perks {
      autoshield {
        name="autoshield"
        price=2
        description="autoshield description"
      }
      immunity {
        name="immunity"
        price=2
        description="autoshield description"
      }
    }
    

    and then in the Settings.scala file get this config:

    val conf = ConfigFactory.load("perks.conf").getConfig("perks")
    

    and then call entrySet on this config and you'll get all the entries not from the root object, but from the perks. Don't forget that Typesafe Config is written in java and entrySet returns java.util.Set, so you need to import scala.collection.JavaConversions._