您的位置:首页 > 其它

scala 模式匹配之Type、Array、List和Tuple

2017-02-16 14:23 806 查看
package com.yy.base

/**
* Scala 模式匹配
* Type Array List Tuple
*/
object PatternMatchMore extends App {

println("-----Type模式匹配------")
def typeMatch(t:Any) = t match{
case c:Int => println(c+"是个整数")
case c:String => println(c+"是个字符串")
case m:Map[_,_] => m.foreach(println)
case _ => println("没有匹配上")
}
//调用
typeMatch(2)
typeMatch("scala")
typeMatch(Map("name"->"yy"))

println("-----Array模式匹配------")
def arrayMatch(arr:Any) = arr match{
case Array(0) => println("Array是一个元素为0的数组")
case Array(x,y) => println("Array有两个元素:" + x +","+y)
case Array(0,_*) => println("Array至少有一个元素,且第一个元素为0")
case _ => println("其他类型的数组")
}
arrayMatch(Array(0))
arrayMatch(Array(0,1))
arrayMatch(Array(0,1,2,3,4,5))
arrayMatch(Array(1,2,3,4,5))

println("-----List模式匹配------")
def listMatch(list:Any) = list match{
case 0::Nil => println("List:0")
case x::y::Nil => println("List:" + x + "," + y)
case 0::tail => println("List:0......"+tail)
case _ => println("其他类型的List")
}
listMatch(List(0))
listMatch(List(1,2))
listMatch(List(0,1,2,3,4,5))
listMatch(List(1,2,3,4,5))

println("-----Tuple模式匹配------")
def tupleMatch(t:Any) = t match{
case (0,_) => println("Tuple start with 0")
case (x,0) => println("Tuple start with " + x)
case _ => println("其他类型的Tuple")
}
tupleMatch((0,"yy"))
tupleMatch(("xx",0))
tupleMatch((0,1,2,3))
}


Spark Master启动入口:

package org.apache.spark.deploy.master

@tailrec
private def parse(args: List[String]): Unit = args match {
case ("--ip" | "-i") :: value :: tail =>
Utils.checkHost(value, "ip no longer supported, please use hostname " + value)
host = value
parse(tail)

case ("--host" | "-h") :: value :: tail =>
Utils.checkHost(value, "Please use hostname " + 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)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  scala