将Typesafe配置解析为案例类

时间:2017-12-19 21:46:27

标签: scala adt case-class typesafe-config

什么是适合解析的案例类

input {
    foo {
      bar = "a"
      baz = "b"
    }

    bar {
      bar = "a"
      baz = "c"
      other= "foo"
    }
}

来自类型安全的HOCON配置https://github.com/kxbmap/configs

如何通过ADT读取?看看他们的例子我不知道如何构建一个类层次结构,其中一些类具有不同数量的字段 - 但可以继承一些。

sealed trait Tree
case class Branch(value: Int, left: Tree, right: Tree) extends Tree
case object Leaf extends Tree

我的示例:

import at.tmobile.bigdata.utils.config.ConfigurationException
import com.typesafe.config.ConfigFactory
import configs.syntax._

val txt =
  """
    |input {
    |    foo {
    |      bar = "a"
    |      baz = "b"
    |      type = "foo"
    |    }
    |
    |    bar {
    |      bar = "a"
    |      baz = "c"
    |      other= "foo"
    |      type="bar"
    |    }
    |}
  """.stripMargin

val config = ConfigFactory.parseString(txt)
config

sealed trait Input{ def bar: String
  def baz:String }
case class Foo(bar: String, baz: String) extends Input
case class Bar(bar:String, baz:String, other:String)extends Input

config.extract[Input].toEither match {
  case Right(s) => s
  case Left(l) =>
    throw new ConfigurationException(
      s"Failed to start. There is a problem with the configuration: " +
        s"${l.messages.foreach(println)}"
    )
}

失败了:

No configuration setting found for key 'type'

1 个答案:

答案 0 :(得分:1)

如果input配置始终包含2个字段(如示例中的txt值;即只有foobar),那么您可以这样做:

val txt =
  """
    |input {
    |    foo {
    |      bar = "a"
    |      baz = "b"
    |      type = "foo"
    |    }
    |
    |    bar {
    |      bar = "a"
    |      baz = "c"
    |      other = "foo"
    |      type = "bar"
    |    }
    |}
  """.stripMargin

sealed trait Input {
  def bar: String
  def baz: String
}
case class Foo(bar: String, baz: String) extends Input
case class Bar(bar: String, baz: String, other:String) extends Input

case class Inputs(foo: Foo, bar: Bar)

val result = ConfigFactory.parseString(txt).get[Inputs]("input")
println(result)

输出:

Success(Inputs(Foo(a,b),Bar(a,c,foo)))

-

如果您打算设置序列的通用输入,那么您应该在配置中对此进行反映并解析Seq[Input]

val txt =
  """
    |inputs = [
    |    {
    |      type = "Foo"
    |      bar = "a"
    |      baz = "b"
    |    }
    |
    |    {
    |      type = "Bar"
    |      bar = "a"
    |      baz = "c"
    |      other= "foo"
    |    }
    |]
  """.stripMargin

sealed trait Input {
  def bar: String
  def baz: String
}
case class Foo(bar: String, baz: String) extends Input
case class Bar(bar: String, baz: String, other: String) extends Input

val result = ConfigFactory.parseString(txt).get[Seq[Input]]("inputs")
println(result)    

输出:

Success(Vector(Foo(a,b), Bar(a,c,foo)))