前言
Spark參數解析的代碼我鬱悶了好一陣子,後面終於在快學Scala中看到的這種寫法,記錄一下。
關鍵源碼
MasterArguments參數解析的時候有這麼一段:
private def parse(args: List[String]): Unit = args match {
case ("--ip" | "-i") :: value :: tail =>
Utils.checkHost(value)
host = value
parse(tail)
case ("--host" | "-h") :: value :: tail =>
Utils.checkHost(value)
host = value
parse(tail)
case ("--port" | "-p") :: IntParam(value) :: tail =>
port = value
parse(tail)
case "--webui-port" :: IntParam(value) :: tail =>
webUiPort = value
parse(tail)
case ("--properties-file") :: value :: tail =>
propertiesFile = value
parse(tail)
case ("--help") :: tail =>
printUsageAndExit(0)
case Nil => // No-op
case _ =>
printUsageAndExit(1)
}
這個功能我們其實是知道,就是我們在啓動Master的時候會傳入類似
-i HOST, --ip HOST 這種參數,然後會解析,但是那個case語法有點奇怪,我把這部分功能單獨抽取出來了:
object ParamParser {
var tableName:String=_
var memory:String=_
def main(args: Array[String]): Unit = {
val list=List("--table","temp.test_table","--memory","4G")
parse(list)
print(tableName)
print(memory)
}
//實際就是匹配特定的一段
def parse(list:List[String]):Unit= list match {
case "--table" :: value :: tail =>{
tableName=value
parse(tail)
}
case "--memory" :: value :: tail=>{
memory=value;
}
case Nil=>
}
}
這個語法關鍵的部分其實是scala中list的模式匹配,
case “–table” :: value :: tail 語義其實就是匹配這種結構
“–table”::接下來的元素::其他元素,tail就是其他的意思,這種結構連到一起就是匹配上的,所以參數裏面的寫法"–table","temp.test_table"會被匹配上,value則取值就是temp.test_table.
總結
這個地方其實還是對scala的語法上面掌握不夠導致的,scala其實裏頭很多很騷氣的寫法,學習還需要加深才行!