簡體   English   中英

在Scala中擴展Scopt OptionParser

[英]Extending Scopt OptionParser in Scala

我正在嘗試使用帶有一些默認參數的基本選項解析器。

在其他項目中,我想用其他參數擴展選項解析器。

就像是:

case class Config(foo: String = null)

trait DefaultParser { self: OptionParser[Config] =>
  opt[String]('f', "foo") action { (x, c) =>
    c.copy(foo = x)
  }
}

case class MyConfig(bar: String = "hello world")

trait MyParser { self: OptionParser[MyConfig] =>
  opt[String]('b', "bar") action { (x, c) =>
    c.copy(bar = x)
  }
}

我是Scala的新手,我不知道我現在怎么能在同一個args上使用它們。

我正在使用Scala 2.10和scopt_2.10 v3.3.0。

我打開了https://github.com/scopt/scopt/issues/132

到目前為止,我能夠提出的最好的結合是兩個解析器。

case class OutputOpts(
  val outputOption: Int = 1
)

trait OptsWithOutput {
  def output: OutputOpts
}

此解析器位於父類中。

def parseOutputOpts(args: Array[String]): OutputOpts = {
  val parser = new scopt.OptionParser[OutputOpts]("scopt") {
    override def errorOnUnknownArgument = false

    opt[Int]("outputOption") action { (x, c) =>
      c.copy(outputOption = x)
    } text ("some output option")
  }

  parser.parse(args, OutputOpts())
    .getOrElse(throw new Exception("Error parsing output cli args"))
}

子類現在可以使用:

case class ChildOpts(
  childThing: Int = 42,
  output: OutputOpts = OutputOpts()
) extends OptsWithOutput

它的解析器結合了兩者。

val opts = ChildOpts(output = super.parseOutputOpts(args))

val parser = new scopt.OptionParser[ChildOpts]("scopt") {
  override def errorOnUnknownArgument = false

  opt[Int]("childThing") action { (x, c) =>
    c.copy(childThing = x)
  } text ("some child thing")
}

parser.parse(args, opts).getOrElse(throw new Exception("failed"))

請注意我們如何將errorOnUnknownArgument設置為false ,這絕對不是理想的並且會導致警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM