在类型安全配置中迭代字段

Ego*_*lko 16 scala typesafe

我有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"
}
Run Code Online (Sandbox Code Playgroud)

我想在我的应用程序中迭代这样的特权:

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"))
}
Run Code Online (Sandbox Code Playgroud)

但我找不到从config返回所有条目的适当方法.我尝试过config.root(),但似乎它返回所有属性,包括system,akka和许多其他属性.

Yur*_*ish 35

entrySet折叠树.如果您只想迭代直接孩子,请使用:

conf.getObject("perks").asScala.foreach({ case (k, v) => ... })
Run Code Online (Sandbox Code Playgroud)

k 将是"autoshield"和"免疫力",但不是"autoshield.name","autoshield.price"等.

这需要您导入scala.collection.JavaConverters._.


4le*_*x1v 20

例如,您的代码中包含以下代码 Settings.scala

val conf = ConfigFactory.load("perks.conf")
Run Code Online (Sandbox Code Playgroud)

如果你调用entrySetroot配置(不是conf.root(),但是这个配置的根对象),它将返回许多垃圾,你需要做的是将所有的特权放在perks.conf中的某个路径下:

perks {
  autoshield {
    name="autoshield"
    price=2
    description="autoshield description"
  }
  immunity {
    name="immunity"
    price=2
    description="autoshield description"
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在Settings.scala文件中获取此配置:

val conf = ConfigFactory.load("perks.conf").getConfig("perks")
Run Code Online (Sandbox Code Playgroud)

然后在此配置上调用entrySet,您将获得所有不是来自根对象的条目,而是来自特权.不要忘记Typesafe Config是用java编写的,并且entrySet返回java.util.Set,因此您需要导入scala.collection.JavaConversions._