Scala基础—模式匹配与case class示例

时间:2022-10-29 05:52:06
package com.spark.scala.basics

import scala.collection.immutable.HashMap

/**
* 1.值匹配
* 2.类型匹配
* 3.集合匹配
* 4.class匹配
* 5.Option
*/

class DataFrameWork
case class ComputationFrameWork(name: String, popular: Boolean) extends DataFrameWork
case class StorageFrameWork(name: String, popular: Boolean) extends DataFrameWork

object PatternMatch {
def main(args: Array[String]): Unit = {
getSalary("scala", 2)
getSalary("java", 3)

getMatchType(100.00)

getMatchCollection(Array("Spark", "Hadoop", "Storm"))

getBigDataType(ComputationFrameWork("Spark", true))

getValue("Spark", HashMap("Spark" -> "Hostest!", "Hadoop" -> "Host!"))
}

// 值匹配
def getSalary(name: String, age: Int): Unit = {
name match {
case "Spark" => println("$150,000")
case "Hadoop" => println("$100,000")
case _ if name == "scala" => println("$140,000")
case _name if age >=3 => println("name: " + _name + " age: " + age + ", $120,000")
case _ => println("$90,000")
}
}

// 类型匹配
def getMatchType(msg: Any): Unit = {
msg match {
case i : Int => println("Integer")
case s : String => println("String")
case d : Double => println("Double")
case array : Array[String] => println("Array")
case _ => println("Unkown type!")
}
}

//集合匹配
def getMatchCollection(msg: Array[String]): Unit = {
msg match {
case Array("Scala") => println("1")
case Array("Scala","java") => println("2")
case Array("Spark", _*) => println("lots of")
case _ => println("Unkown type!")
}
}

//class 匹配
def getBigDataType(data : DataFrameWork): Unit = {
data match {
case ComputationFrameWork(name, popular) => println(name + "-" + popular)
case StorageFrameWork(name, popular) => println(name + "-" + popular)
case _ => println("Other type")
}
}

// Option
def getValue(key : String, content: HashMap[String, String]): Unit = {
content.get(key) match {
case Some(value) => println(value)
case None => println("Not Found!")
}
}

}

package com.expgiga.ScalaTest

/**
*
*/
object SpecifyParameterTest {
def main(args:Array[String]): Unit = {
val alice = Person("Alice", 1)
val bob = Person("Bob", 2)
val charlie = Person("Charlie", 3)

for (person <- List(alice, bob, charlie)) {
person match {
case Person("Alice", 1) => println("Hi, Alice!")
case Person("Bob", 2) => println("Hi, Bob!")
case Person(name, age) =>
println("Age: " + age, " year, name: " + name + "?")
}
}

println("------------------------------------------------")
println(matchTest(1))
println(matchTest("two"))
println(matchTest(3))
println(matchTest("pipixia"))

}

case class Person(name: String, age: Int)


def matchTest(x: Any): Any = x match {
case 1 => "one"
case "two" => 2
case y: Int => "scala.Int"
case _ => "many"
}
}
/*
在声明case class时,发生了:
1.构造器的每个参数都成为val,除非显式被声明为var,但是并不推荐这么做
2.在伴生对象中提供了apply方法,所以可以不使用new关键字就可以构建对象
3.提供unapply方法使模式匹配可以工作
4.生成toString, equals, hashCodecopy方法,除非显式给出这些方法的定义
*/