我有以下 HOCON 配置:
a {
b.c.d = "val1"
d.f.g = "val2"
}
HOCON 将路径“bcd”和“dfg”表示为对象。所以,我想要一个阅读器,它将这些配置读取为 Map[String, String],例如:
Map("b.c.d" -> "val1", "d.f.g" -> "val2")
我创建了一个阅读器并尝试以递归方式进行操作:
import scala.collection.mutable.{Map => MutableMap}
private implicit val mapReader: ConfigReader[Map[String, String]] = ConfigReader.fromCursor(cur => {
def concat(prefix: String, key: String): String = if (prefix.nonEmpty) s"$prefix.$key" else key
def toMap(): Map[String, String] = {
val acc = MutableMap[String, String]()
def go(
cur: ConfigCursor,
prefix: String = EMPTY,
acc: MutableMap[String, String]
): Result[Map[String, Object]] = {
cur.fluent.mapObject { obj =>
obj.value.valueType() match {
case ConfigValueType.OBJECT => go(obj, concat(prefix, obj.pathElems.head), acc)
case ConfigValueType.STRING =>
acc += (concat(prefix, obj.pathElems.head) -> obj.asString.right.getOrElse(EMPTY))
}
obj.asRight
}
}
go(cur, acc = acc)
acc.toMap
}
toMap().asRight
})
它给了我正确的结果,但有没有办法在这里避免 MutableMap?
PS 另外,我想通过“pureconfig”阅读器继续实施。