Neel
Neel

Reputation: 595

How can I use scopt in Scala to get all of the remaining arguments?

I'm using the scopt library: https://github.com/scopt/scopt

I see that I can define a case class with option names if I know them beforehand. What if I don't know the names of the options that the user will pass? Is there any way for me to capture those option values in a dictionary or something?

Thanks!

Upvotes: 0

Views: 3078

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

Try opt[Map[String,String]] like so

case class Config(args: Map[String, String] = Map())

object Hello extends App {
  val parser = new scopt.OptionParser[Config]("scopt") {
    head("scopt", "3.x")
    opt[Map[String,String]]("args").valueName("k1=v1,k2=v2...").action( (x, c) =>
      c.copy(args = x) ).text("other arguments")
  }

  parser.parse(args, Config()) match {
    case Some(config) => println(config)
    case None =>
    // arguments are bad, error message will have been displayed
  }
}

which on executing with

run --args key1=val1,key2=val2

outputs

Config(Map(key1 -> val1, key2 -> val2))

Upvotes: 3

Related Questions