scala 命令台参数解析

sliding :


object SlidingParser extends App{
var name = ""
var port = 0
var ip = ""
args.sliding(2, 2).toList.collect {
case Array("-a", argIP: String) => ip = argIP
case Array("-b", argPort: String) => port = argPort.toInt
case Array("-c", argName: String) => name = argName
}
println(name)
println(port)
println(ip)
}

Pattern matching :


object Parser {
  val usage =
    """
    Usage: spark-submit --master=yarn xx.jar [-h] [-p] <inputCsvPath> [-o] <outputLogPath> [-f] <testFuncName>
  """
  type OptionMap = Map[Symbol, String]

  def nextOption(map: OptionMap, list: List[String]): OptionMap = {
    list match {
      case Nil => map
      case "-h" :: other =>
        nextOption(map ++ Map('help -> usage), other)
      case "-p" :: value :: tail =>
        nextOption(map ++ Map('inputCsvPath -> value.toString), tail)
      case "-o" :: value :: tail =>
        nextOption(map ++ Map('outputLogPath -> value.toString), tail)
      case "-f" :: value :: tail =>
        nextOption(map ++ Map('funcName -> value.toString), tail)
      case "-t" :: value :: tail =>
        nextOption(map ++ Map('perfTestTimes -> value.toString), tail)
      case "-s" :: tail =>
        nextOption(map ++ Map('showFlag -> true.toString), tail)
      case option :: tail =>
        nextOption(map, tail)
    }
  }
}
原文地址:https://www.cnblogs.com/mangoczp/p/12803778.html