scala学习笔记09_模式匹配
1. 基本模式匹配
object MatchDemo {
def main(args: Array[String]): Unit = {
var result = ""
val code = "600";
code match {
case "200"=>{
result = "ok"
println("code 200,status ok");
}
case "404" =>{
result = "wrong way"
println("code 404,wrong way")
}
case "500" =>{
result = "service down"
println("code 500,service down")
}
case code22 => println("code value assign code22.code22 = "+code22)
case _=>{
if(code == "600"){
result = "very special"
println("code 600,very special")
}
}
}
}
}
2. 类型匹配
object MatchDemo2 {
/**
* 类型匹配
* 1.类型匹配不考虑泛型
* 2.Array[Int]不属于泛型
* @param args
*/
def main(args: Array[String]): Unit = {
var ai:Array[Int] = Array(1,2,3);
val ints: List[Int] = List(1, 2, 3)
val goal = List(ai, ints)
for(item<-goal){
item match {
case ab:Array[Int]=>{ //将需要匹配内容直接赋值给ab。
println("类型Array[Int]")
for(subItem<-ab){
println(subItem)
}
}
case _:List[String]=>{ //泛型不计较
println(item)
}
case _=>{
println("防异常")
}
}
}
}
}
3. 数组匹配
/**
* 数组匹配
*/
object ArrayMatch {
def main(args: Array[String]): Unit = {
for (arr <- Array(Array(0), Array(1), Array(0, 1, 0))) {
val result = arr match {
case Array(0) => "完全匹配"
case Array(_) => "个数匹配,不赋值"
case Array(x, y) => "个数匹配,并赋值"
case Array(0, _*) => "开头值匹配,通配符匹配"
case _ => "没有匹配到"
}
println("result = " + result)
}
}
}
4 List匹配
object ListMatch {
def main(args: Array[String]): Unit = {
val list = List(List(0), List(1, 2), List(3), List(3,6,9))
for(item<-list){
var result = item match {
case 0 :: Nil=>"全匹配"
case x::y::Nil=>"个数匹配并赋值 x="+x
case 3::tail =>"3打头"
case _=>"default"
}
println(result)
}
}
}
4.1 元素匹配(for)
/**
* 模式匹配在for中
* 匹配具体元素
*/
object Match4For {
def main(args: Array[String]): Unit = {
val map = Map("A"->1, "B"->0, "C"->3)
//(k, v),匹配全部
/*for ( (k, v) <- map ) {
println(k + " -> " + v)
}*/
//(k, 0) 匹配(k,0)
for ((k, 0) <- map) {
println(k + " " + 0)
}
//说明
for ((k, v) <- map if v == 0) {
println(k + " " + v)
}
}
}
5 元组匹配
/**
* 元组匹配
*/
object TupleMatch {
def main(args: Array[String]): Unit = {
for (pair <- Array((0, 1), (1, 0), (1, 1),(1,0,2))) {
val result = pair match { // pair 表示匹配的是对偶元组
case (0, _) => "匹配第一个元素为0的对偶元组"
case (y, 0) => "匹配第二个元素为0的对偶元组,并且赋值 y="+y
case _ => "default"
}
println(result)
}
}
}
6 对象匹配
class User(val name: String, val age: Int)
object User{
def apply(name: String, age: Int): User = new User(name, age)
//析构函数
def unapply(user: User): Option[(String, Int)] = {
println("enter unapply..")
if (user == null)
None
else
Some(user.name, user.age)
}
}
object TestMatchUnapply {
def main(args: Array[String]): Unit = {
val user: User = User("zhang", 11)
val result = user match {
case User("zhang", 12) => "对象匹配"
case User("zhang", 11) => "对象匹配会触发unapply,判断对象属性值是否一致"
case _ => "default"
}
println(result)
}
}
- 1 样例类
/**
*
* ①样例类仍然是类,和普通类相比,只是其自动生成了伴生对象,并且伴生对象中自动提供了一些常用的方法,如apply、unapply、toString、equals、hashCode和copy。
②样例类是为模式匹配而优化的类,因为其默认提供了unapply方法,因此,样例类可以直接使用模式匹配,而无需自己实现unapply方法。
③构造器中的每一个参数默认为val,除非它被显式地声明为var(不建议这样做)。
————————————————
版权声明:本文为CSDN博主「布莱恩特888」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41818801/article/details/106177221
*/
// 使用样例类
case class CaseUser(name: String, age: Int)
object matchUnapply {
def main(args: Array[String]): Unit = {
val user: CaseUser = CaseUser("zhangsan", 11)
val result = user match {
case CaseUser("zhangsan", 11) => "yes,same!"
case _ => "no"
}
println(result)
}
}
7 嵌套匹配
/**
* 匹配嵌套结构
*/
abstract class Item
case class Article(description: String, price: Double) extends Item
case class Bundle(description: String, discount: Double, item: Item*) extends Item
object NestingMatch{
def main(args: Array[String]): Unit = {
val regular = Article("《飘》", 40);
val sale = Bundle("大甩卖系列", 10,
Article("《春》", 40),
Bundle("《夏》", 20,
Article("《秋》", 80),
Article("《冬》",30)))
//将descr绑定到第一个Article的描述,打印书名
val result1 = sale match {
case Bundle(_, _, Article(descr, _), _*) => descr
}
println(result1)
//_*绑定剩余Item到rest
//通过@表示法将嵌套的值绑定到变量。
val result2 = sale match {
case Bundle(_, _, art @ Article(_, _), rest @ _*) => (art, rest)
}
println(result2)
//不使用_*绑定剩余Item到rest
val result3 = sale match {
case Bundle(_, _, art @ Article(_, _), rest) => (art, rest)
}
println(result3)
//计算某个Item价格的函数,并调用
def begprice(it: Item): Double = {
it match {
case Article(_, p) => p
case Bundle(_, disc, its@_*) => its.map(begprice _).sum - disc
}
}
println(begprice(sale)) //传入Bandle,折扣10块钱
println(begprice(regular)) //传入Article对象,直接输出价格
}
}
8 密封类
/**
* 密封类的继承类只能在当前文件中
*/
sealed class SealedDemo {
}