Search code examples
scalagetopt

Simple functional getopt in Scala


def main(args: Array[String]) {
  if (args.length == 0) println(usage)
  val argList = args.toList
  type OptionMap = Map[Symbol, Any]

  def nextOption(map: OptionMap, list: List[String]): OptionMap = {
    list match {
      case Nil => map
      case "-h" | "--help" :: tail => usage(); sys.exit(0)
      case "-p" | "--port" :: option :: tail => nextOption(map ++ Map('port -> option.toInt), tail)
  }
}

Is there any way to catch more head values in List? This code generates

type mismatch;
   found   : String("-h")
   required: List[String]
        case "-h" | "--help" :: tail => usage(); sys.exit(0)
             ^

possible duplicate: Best way to parse command-line parameters?


Solution

  • Just wrap the code in parentheses:

    case ("-h" | "--help") :: tail => usage(); sys.exit(0)
    

    Without the parentheses, the compiler interprets the code as

    case ("-h") | ("--help" :: tail) => usage(); sys.exit(0)
    

    which is not want you want.