一:基本语法
package chapter07
object Test01_PatternMatchBase {
def main(args: Array[String]): Unit = {
//1.基本定义语法
val x:Int = 2
val y:String = x match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
println(y)//根据x的值,输出y的值,这个案例会输出two
//2.示例:用模式匹配实现简单的二元运算
val a = 25
val b = 13
def matchDualOp(op:Char) = op match {
case '+' => a + b
case '-' => a - b
case '*' => a * b
case '/' => a / b
case '%' => a % b
case _ => -1
}
println(matchDualOp('+'))
//3.模式守卫
//求一个整数的绝对值
def abs(num:Int):Int = {
num match {
case i if i>= 0 => i
case i if i<0 => -i
}
}
println(abs(67))
}
}
二:匹配常量-匹配类型、数组、列表、元组
package chapter07
object Test02_MatchTypes {
def main(args: Array[String]): Unit = {
//1.匹配常量
def describeConst(x:Any):String = x match {
case 1 => "Int one"
case "hello" => "String hello"
case true => "Boolean true"
case '+' => "Char +"
case _ => ""
}
println(describeConst("hello"))
//2.匹配类型
def describeType(x:Any):String = x match {
case i:Int => "Int" + i
case s:String => "String" + s
case list:List[String] => "List" + list
case array:Array[Int] => "Array[Int]" + array.mkString(",")
case a => "something else:" + a
}
println(describeConst(35))
//3.匹配数组
for (arr <- List(
Array(0),
Array(1,0),
Array(0,1,0),
Array(1,1,0),
Array(2,3,7,15),
Array("hello",20,30)
)){
val result = arr match {
case Array(0) => "0"
case Array(1,0) => "Array(1,0)"
case Array(x,y) => "Array:" + x + "," + y
case Array(0,_*) => "以0开头的数组"
case Array(x,1,z) => "中间为1的三元素数组"
case _ => "something else"
}
println(result)
}
//4.匹配列表--方式一
for(list <- List(
List(0),
List(1,0),
List(0,0,0),
List(1,1,0),
List(88),
)){
val result = list match {
case List(0) => "0"
case List(x,y) => "List(x,y):" + x + "," + y
case List(0,_*) => "List(0....)"
case List(a) => "List(a):" + a
case _ => "something else"
}
println(result)
}
//4.匹配列表--方式二
val list = List(1,2,5,7,24)
val result = list match {
case first::second::rest => println(s"first:$first,second:$second,rest:$rest")
case _ => println("something else")
}
println(result)
//5.匹配元组
for(tuple <- List(
(0,1),
(0,0),
(0,1,0),
(0,1,1),
(1,23,56),
("hello",true,0.5),
)){
val result = tuple match {
case (a,b) => "" + a + "," + b
case (0,_) => "(0,_)"
case (a,1,_) => "(a,1,_)" + a
case _ => println("something else")
}
println(result)
}
}
}
package chapter07
object Test03_MatchTupleExtend {
def main(args: Array[String]): Unit = {
//1.在变量声明时匹配
val (x,y) = (10,"hello")
println(s"x:$x,y:$y")
val List(first,second,_*) = List(23,15,9,78)
val fir::sec::rest = List(23,15,9,18)
println(s"first:$fir,second:$sec,res:$rest")
//for推导式进行模式匹配
val list:List[(String,Int)] = List(("a",12),("b",35),("c",27))
for (elem <- list){
println(elem._1 + " " +elem._2)
}
//将list元素直接定义为元组,对变量赋值
for((word,count) <- list){
println(word + " " + count)
}
//可以不考虑某个位置的变量,只遍历key或者value
for((word,_) <- list){
println(word)
}
//可以指定某个位置的值必须时多少
for(("a",count) <- list){
println(count)
}
}
}
三:匹配对象以及样例类
package chapter07
object Test_MatchObject {
def main(args: Array[String]): Unit = {
val student = new Student("alice",18)
//针对对象实例的内容进行匹配
val result = student match {
case Student("alice",18) => "Alice,18"
case _=> "Else"
}
println(result)
}
}
//定义类
class Student(val name:String,val age:Int)
//定义伴生对象
object Student{
def apply(name: String, age: Int): Student = new Student(name, age)
//必须实现unapply方法,用来对对象属性进行拆解
def unapply(student: Student): Option[(String, Int)] = {
if(student == null){
None
}else{
Some((student.name,student.age))
}
}
}
package chapter07
object Test05_MatchCaseClass {
def main(args: Array[String]): Unit = {
val student = Student("alice",18)
//针对对象实例的内容进行匹配
val result = student match {
case Student("alice",18) => "Alice,18"
case _=> "Else"
}
println(result)
}
}
//定义样例类
case class Student(val name:String,val age:Int)
四:异常处理机制
package chapter08
object Test01_Exception {
def main(args: Array[String]): Unit = {
try{
val n = 10 / 0
}catch {
case e:ArithmeticException => {
println("发生算术异常")
}
case e:Exception => {
println("发生一般异常")
}
}finally {
println("处理结束")
}
}
}
五:隐式转换-隐式参数-隐式值-隐式函数
package chapter08
object Test02_Implcit {
def main(args: Array[String]): Unit = {
//隐式函数
implicit def convert(num:Int):MyRichInt = new MyRichInt(num)
println(12.myMax(15))
//隐式类
implicit class MyRichInt(val self:Int){
//自定义比较大小的方法
def myMax(n:Int):Int = if (n < self) self else n
def myMin(n:Int):Int = if (n < self) n else self
}
println(12.myMin(2))
//隐式参数,同一作用域,相同类型只能有一个,隐式值会覆盖默认值
implicit val str:String = "alice"
def sayHello(implicit name:String):Unit ={
println("hello," + name)
}
sayHello
}
}
/*
//自定义类
class MyRichInt(val self:Int){
//自定义比较大小的方法
def myMax(n:Int):Int = if (n < self) self else n
def myMin(n:Int):Int = if (n < self) n else self
}*/
六:泛型-协变和逆变
package chapter08
object Test03_Generics {
def main(args: Array[String]): Unit = {
//协变和逆变
val child:Parent = new Child
val childList:MyCollecion[Parent] = new MyCollecion[Child]
}
}
//定义继承
class Parent{}
class Child extends Parent{}
class SubChild extends Child{}
//定义泛型的集合类型
class MyCollecion[E]{}

七:泛型的上下限
Class PersonList[T<:Person]{ //泛型上限
}
Class PersonList[T>:Person]{ //泛型下限
}
本文介绍Scala中的模式匹配概念,包括基本语法、匹配常量、类型、数组、列表、元组等,还介绍了如何通过模式匹配来处理对象及样例类。
946

被折叠的 条评论
为什么被折叠?



