scopt

Using a custom class in command option

Environment:

  • Scala: 2.13.1
  • scopt: 4.0.0-RC2

According to the scopt documentation, a command option can be defined as opt[A]("o", "option") (or opt[A]('o')), where A is any type that is an instance of Read typeclass.

In this example, we will add a mode command option of type ServerMode:

  1. Create an object ServerMode extending Enumeration class, which contains the option possible values:
object ServerMode extends Enumeration {
  type ServerMode = Value
  val ECHO, HELLO = Value
}
  1. In Config case class, define the mode option of type ServerMode with the default value:
mode: ServerMode = ServerMode.HELLO
  1. Add mode option as a command child:
opt[ServerMode]('m', "serverMode").action((x, c) => c.copy(mode = x)).text("Server mode").required()

A command mode option value can be specified in the following way:

command ... -m ECHO