本篇文章主要采用实际例子来说明Scala的模式匹配问题:
package com.dt.sparkApps.sql
//模式匹配的类准备
class DataFrameWork
case class ComputationFrameWork(name : String, popular : Boolean) extends DataFrameWork
case class StorageFrameWork(name : String , popular : Boolean) extends DataFrameWork
object helloPatternMatch {
def main(args: Array[String]): Unit = {
// getSalary(“Spark”)
// getSalary(“Scala”,8)
// getMatchType(8)
// getMatchType(Array(5))
// getMatchcollection(Array(“Spark”,”Scala”))
// getBigDataType(ComputationFrameWork(“Spark”,true))
getValue(“Hadoop” , Map(“Spark” -> “the hottest”,”Hadoop” -> “the olddest”))
}
//模式匹配函数例子
def getSalary(name : String){
name match{
case “Spark” => println(“15/year”)
case _ if name == “Scala” => println(“12/year”)
case "Hadoop" => println("10/year")
case _ => println("8/year")
}
}
//模式匹配函数2个参数
def getSalary(name : String,age : Int){
name match{
// case _name if age > 5 => println(“120/year”)
case _name if age > 5 => println(“name : ” + _name +” “+”age:”+age +” “+”1200/year” )
}
}
//模式匹配之类型
def getMatchType(msg : Any){
msg match{
case arry : Array[Int] => println(“Array”)
case i : Int => println(“Integer”)
case s : String => println(“String”)
case d : Double => println(“Double”)
case _ => println(“UnKnow Type”)
}
}
//数组的模式匹配
def getMatchcollection(msg : Array[String]){
msg match{
case Array(“Scala”) => println(“one element”)
case Array(“Scala”,”Java”) => println(“two element”)
case Array(“Spark”, _* ) => println(“start with Spark”)
case _ => println(“Unknow Type”)
}
}
//模式匹配之类的匹配
def getBigDataType(data : DataFrameWork){
data match{
case ComputationFrameWork(name,popular) => println(“name:”+name +”popular”+popular)
case StorageFrameWork(name,popular) => println(“name:”+name +”popular”+popular)
case _ => println(“some other type”)
}
}
//模式匹配之key,value方式
def getValue(Key : String ,content : Map[String,String]){
content.get(Key) match{
case Some(value) => println(value)
case None => println(“not Found”)
}
}
}
本博客内容来自于 : 简介: 王家林:DT大数据梦工厂创始人和首席专家. 联系邮箱18610086859@126.com 电话:18610086859 QQ:1740415547 微信号:18610086859