Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over fields in typesafe config

Tags:

scala

typesafe

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.

like image 785
Egor Koshelko Avatar asked Jul 11 '13 16:07

Egor Koshelko


2 Answers

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._.

like image 200
Yuri Geinish Avatar answered Sep 28 '22 17:09

Yuri Geinish


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._

like image 21
4lex1v Avatar answered Sep 28 '22 16:09

4lex1v