Scala中的简单函数getopt

cam*_*beh 1 scala getopt

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法捕获更多的头部价值List?此代码生成

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

可能重复:解析命令行参数的最佳方法?

kir*_*uku 9

只需将代码括在括号中:

case ("-h" | "--help") :: tail => usage(); sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

如果没有括号,编译器会将代码解释为

case ("-h") | ("--help" :: tail) => usage(); sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

这不是你想要的.