Reputation: 1172
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?
Upvotes: 1
Views: 1139
Reputation: 53358
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.
Upvotes: 9
Reputation: 1395
Scala's pattern matching allows you to store a match in a variable and then perform conditional checks on that variable.
list match {
case Nil => map
case x :: tail if x == "-h" || x == "--help" => usage(); sys.exit(0)
case y :: option :: tail if y == "-p" || y == "--port" => nextOption(map ++ Map('port -> option.toInt), tail)
}
Upvotes: 3