简体   繁体   English

scala:如何迭代类型安全配置列表

[英]scala: how to iterate typesafe config list

I am trying to iterate over the config List and it's giving me some error.我正在尝试遍历配置列表,它给了我一些错误。 Not sure what I am doing wrong.不知道我做错了什么。

config配置

test{
  header = [
    {
      name="col0"
      vale="aaa"
    }
    {
    name="col1"
    value="bbb"
    }
  ]
}

code代码

val headers:ConfigList  = ConfigFactory.load().getList("test.header")

    headers.forEach{header:Config =>
      val name = header.getString("name")
      println(name)
    }

Error错误

Error:(32, 35) type mismatch;
 found   : com.typesafe.config.Config => Unit
 required: java.util.function.Consumer[_ >: com.typesafe.config.ConfigValue]
    headers.forEach{header:Config =>

As @Luis said, Functions in Scala 2.11.x do are not compiled to Java Functions.正如@Luis 所说,Scala 2.11.x 中的函数不会编译为 Java 函数。 And since they are not Java Functions, they can not be converted to Consumer via SAM.并且由于它们不是 Java 函数,因此无法通过 SAM 将它们转换为Consumer

And so, You will need to explicitly provide a Cosumer .因此,您需要明确提供Cosumer

Also, with getList("...") you get a ConfigList which can be used to iterate over ConfigValue elements and not Config .此外,使用getList("...")你会得到一个ConfigList ,它可以用来迭代ConfigValue元素而不是Config

headers.forEach(new Consumer<ConfigValue> {
  override def accept(configValue: ConfigValue): Unit = {
    // Since you have ConfigValue... do whatever you want with it
    println(configValue.render())
  }
})

What you actually want to use is getConfigList(...)你真正想要使用的是getConfigList(...)

val headers = ConfigFactory.load().getConfigList("test.header")

headers.forEach(new Consumer<Config> {
  override def accept(config: Config): Unit = {
    println(config.getString("name"))
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM