2017-12-19 6 views
2

解析するフィッティングケースクラスは何ですか?解析タイプセーフの設定が

これを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)}" 
    ) 
} 

はで失敗します。input設定はいつもの例のように2フィールド(txt値で構成されます

No configuration setting found for key 'type' 

答えて

1

。すなわち、ちょうど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))) 
+0

残念ながら、これはもう少し複雑で、最初のレイヤ、つまり入力をいくつかの追加値としてスキップすることはできません。 –

関連する問題