/**
* 定义偏函数用PartialFunction
* PartialFunction[T1,T2],T1为传入的参数类型,T2为返回值类型
* 偏函数体中的case只会匹配一个,匹配到了就不会继续往下匹配
*/
val func: PartialFunction[String, Int] = {
case "a" => 1
case "b" => 2
case _ => -1
}
/**
* 匹配字符串
*/
def m1(str: String) = str match {
case "a" => 1
case "b" => 2
case _ => -1
}
/**
* 匹配类型
*/
def m2(x: Any) = x match {
case x: String => println(x)
//带守卫条件
case x: Int if x < 7 => println(x)
case _ => println("unknown")
}
/**
* 匹配数组
*/
def m3(arr: Array[Int]) = arr match {
case Array(0, x, y) => println("匹配以0开头,有三个元素的数组")
case Array(0) => println("匹配只有0元素的数组")
case Array(0, _*) => println("匹配以0开头,任意多个元素组成的数组")
case _
scala 模式匹配
最新推荐文章于 2021-12-30 11:09:02 发布
本文介绍了Scala中的模式匹配,包括使用PartialFunction定义偏函数,匹配字符串、类型、数组、序列和元组的案例,展示了如何在不同场景下进行高效且灵活的匹配操作。
摘要由CSDN通过智能技术生成