Skip to content
Platon Pronko edited this page Dec 7, 2020 · 10 revisions

Scallop is quite extensible when it comes to types of values that you want to extract from your options - you can simply define your own ValueConverter and provide it as implicit value (or pass it manually).

For example, let's define a converter for the Person type (person can have a name and a telephone in this case):

case class Person(name:String, phone:String)

val personConverter = new ValueConverter[Person] {
  val nameRgx = """([A-Za-z]*)""".r
  val phoneRgx = """([0-9\-]*)""".r
  // parse is a method, that takes a list of arguments to all option invokations:
  // for example, "-a 1 2 -a 3 4 5" would produce List(List(1,2),List(3,4,5)).
  // parse returns Left with error message, if there was an error while parsing
  // if no option was found, it returns Right(None)
  // and if option was found, it returns Right(...)
  def parse(s:List[(String, List[String])]):Either[String,Option[Person]] =
    s match {
      case (_, nameRgx(name) :: phoneRgx(phone) :: Nil) :: Nil =>
        Right(Some(Person(name,phone))) // successfully found our person
      case Nil => Right(None) // no person found
      case _ => Left("provide person name") // error when parsing
    }

  val argType = org.rogach.scallop.ArgType.LIST
}

object Conf extends ScallopConf(List("--person", "Pete", "123-45")) {
  val person = opt[Person]()(personConverter)
  verify()
}
Conf.person() shouldBe Person("Pete", "123-45")

Helper methods

If your conversion is quite simple, you can use some helper methods defined in org.rogach.scallop package:

  • singleArgConverter(conv: String => A) - creates a converter for a single-value option. If the conversion failed, you should throw some exception from conv function.

    For example, this is how the intConverter is defined:

    implicit val intConverter = singleArgConverter[Int](_.toInt)
  • listArgConverter(conv: String => A) - almost the same as for single args, but the resulting converter will be usable for multiple-value options.

  • propsConverter(conv: ValueConverter[A]) - used to create new converters for property values. conv is the converter for the elementary value in this case.