【Scala】08 模式匹配 Match Case
由Scala封装的一套match case处理,功能比原Java的更为强大
package cn import scala.collection.immutable.IndexedSeqDefaults.defaultApplyPreferredMaxLength.>=
import scala.collection.immutable.Queue
import scala.collection.mutable object HelloScala {
def main(args: Array[String]): Unit = {
// - - - - - 模式匹配 matchCase - - - - - val a = 2
val b = a match {
case 1 => "one"
case 2 => "one"
case 3 => "one"
case 4 => "one"
case _ => "other"
}
b(a) // - - - - - 实现二元运算 - - - - -
val x = 22
val y = 33 def matchDualOp(op : Char) = op match {
case '+' => x + y
case '-' => x - y
case '*' => x * y
case '/' => x / y
case _ => "uncaught op"
} println(matchDualOp('*'))
println(matchDualOp('&')) // - - - - - 模式守卫 求整数的绝对值 - - - - -
def abs(num : Int) : Int = {
num match {
case i if i >= -1 => i
case i if i < 0 => -i
}
} // - - - - - 模式匹配常量 - - - - -
def descConst(o : Any) : String = o match {
case 1 => "Num ONE"
case "HELLO" => "String HELLO"
case true => "Boolean True"
case '+' => "Char +"
case _ => "don't know val what it is "
} // 模式匹配类型
def descType(x : Any) : String = x match {
case i : Int => "Int " + i
case s : String => "String " + s
case l : List[String] => "List[String] " + l
case ss => "Other Type, But is scala.Any " + ss.getClass
} // - - - - - 模式匹配,匹配数组处理 - - - - -
for(array <- List(
Array(0),
Array(1,0),
Array(0,1,0),
Array(1,1,0),
Array(2,3,7,15),
Array("hello", 10,7,15)
)) {
val res = array match {
case Array(0) => "0"
case Array(1, 0) => "Array(1, 0)"
case Array(x, y) => s"Array($x, $y)" // 匹配两元素的数组
case Array(0, _*) => "First Element is 0" // 匹配开头为0的数组
case Array(x, 1, y) => "0" // 匹配中间为1的三元素数组
case _ => "Something else" // 其他
}
println(res)
} // - - - - - 匹配列表 - - - - -
for(list <- List(
List(1,0),
List(1,0,1),
List(0,0,0),
List(1,1,0),
List(88),
)) {
val result = list match {
case List(0) => "0"
case List(x, y) => s"List($x, $y)"
case List(0, _*) => list.toString() // 要求以0开头的List
case List(a) => s"List($a)" // 只有一个元素的List
case _ => "Something else"
}
println(result)
} // - - - - - 方式 - - - - -
val list = List(1, 2, 5, 7, 24) list match {
case first :: second :: reset => {
// first = 1, second = 2, reset = List(5, 7, 24)
println(s" first = $first, second = $second, reset = $reset")
}
case _ => println("Something else")
} // 匹配元组
for(tuple <- List(
(0,1),
(0,0),
(0),
(1),
(0,1,1),
(1, 23,56),
("hello", true, 0.5),
)) {
val result = tuple match {
case (a, b) => s"tuple($a, $b)"
case (0, _) => s"tuple(0, _)"
case (a, 1, 0) => "(a, 1, _)"
case (x, y, z) => s"($x, $y, $z)"
case _ => "something else"
}
println(result)
} }
}
对变量进行模式匹配和类型 推导
package cn import scala.collection.immutable.IndexedSeqDefaults.defaultApplyPreferredMaxLength.>=
import scala.collection.immutable.Queue
import scala.collection.mutable object HelloScala {
def main(args: Array[String]): Unit = {
// 变量声明匹配处理
val (x, y) = (10, "string")
println(x) val List(a, b, _*) = List(1, 3, 4, 8, 33) val valA :: valB :: others = List(1, 3, 4, 8, 33) // 类似 JS的反向赋值,这些声明的集合的变量都可以被访问调用 val list2 = List(
("a", 88),
("b", 188),
("c", 288),
("d", 388),
("e", 488),
)
// For循环的迭代对象 类型推导
for( (key, value) <- list2) {
println(s"($key, $value)") // 可以直接获取
} // 或者按缺省参数处理 只获取其中的一个
for( (key, _) <- list2) {
println(s"($key)") // 可以直接获取
} // 或者用于具体匹配
for( ("a", ccc) <- list2) {
println(s"($ccc)") // 可以直接获取
} }
}
自定义对象的模式匹配:
package cn
object HelloScala {
def main(args: Array[String]): Unit = {
// 对象匹配&样例类
val student = new Student("alice", 19)
val res = student match {
case Student("alice", 19) => "Alice, 19"
case _ => "Else"
}
println(res)
}
}
class Student(val name : String, val age : Int)
// 需要伴生对象支持
object Student {
def apply(name : String, age : Int) : Student = new Student(name, age)
/**
* 使用对象匹配需要这个unapply方法来支持
* @param student
* @return
*/
def unapply(student: Student) : Option[(String, Int)] = {
if (null == student) None
else Some( (student.name, student.age))
}
}
样例类就是把上面的内容做好了封装处理,只需要case前缀声明一下类
package cn
object HelloScala {
def main(args: Array[String]): Unit = {
// 对象匹配&样例类
val student = new Student("alice", 19)
val res = student match {
case Student("alice", 19) => "Alice, 19"
case _ => "Else"
}
println(res)
}
}
// 样例类已经封装好处理,声明完成即可直接用来模式匹配
case class Student(val name : String, val age : Int)
【Scala】08 模式匹配 Match Case的更多相关文章
- Scala学习文档-样本类与模式匹配(match,case,Option)
样本类:添加了case的类便是样本类.这种修饰符可以让Scala编译器自动为这个类添加一些语法上的便捷设定. //样本类case class //层级包括一个抽象基类Expr和四个子类,每个代表一种表 ...
- scala里的模式匹配和Case Class
模式匹配的简介 scala语言里的模式匹配可以看作是java语言中switch语句的改进. 模式匹配的类型 包括:常量模式.变量模式.构造器模式.序列模式.元组模式以及变量绑定模式等. 常量模式匹配 ...
- Scala中的match(模式匹配)
文章来自:http://www.cnblogs.com/hark0623/p/4196261.html 转载请注明 代码如下: /** * 模式匹配 */ case class Class1(pa ...
- scala高级内容(一) Case Class
一. 操作符 自定义操作符 操作付默认左结合调用.除了以:结尾的操作符是右结合调用 object OperaterTest extends App{ val a: myInt = new myInt( ...
- 聊聊 scala 的模式匹配
一. scala 模式匹配(pattern matching) pattern matching 可以说是 scala 中十分强大的一个语言特性,当然这不是 scala 独有的,但这不妨碍它成为 sc ...
- 【scala】模式匹配
Scala的模式匹配是通过match表达式从若干可选项中选择,类似Java中的switch. 例子: val firstArg = if(args.length>0) args(0) else ...
- Scala之模式匹配(Patterns Matching)
前言 首先.我们要在一開始强调一件非常重要的事:Scala的模式匹配发生在但绝不仅限于发生在match case语句块中.这是Scala模式匹配之所以重要且实用的一个关键因素!我们会在文章的后半部分具 ...
- scala 常用模式匹配类型
模式匹配的类型 包括: 常量模式 变量模式 构造器模式 序列模式 元组模式 变量绑定模式等. 常量模式匹配 常量模式匹配,就是在模式匹配中匹配常量 objectConstantPattern{ def ...
- Scala学习——模式匹配
scala模式匹配 1.基础match case(类似java里switch case,但功能强大些) object MatchApp { def main(args: Array[String]): ...
- scala学习手记40 - case表达式里的模式变量和常量
再来看一下之前的一段代码: def process(input: Any) { input match { case (a: Int, b: Int) => println("Proc ...
随机推荐
- java.sql.SQLException: MONTH 报错解决方法
idea控制台报错:java.sql.SQLException: MONTH Error attempting to get column 'xxx' from result set. Cause: ...
- css3 浏览器前缀 线型渐变 过渡属性
css3:没有形成正式版 每个浏览器商,为了能对css3属性形成一个更好的支持,浏览器形成自己一套语法规范,一些css属性,如果想在浏览器上形成支持,有时候需要添加浏览器前缀 谷歌前缀:-webkit ...
- ETL工具-nifi干货系列 第九讲 处理器EvaluateJsonPath,根据JsonPath提取字段
1.其实这一节课本来按照计划一起学习RouteOnAttribute处理器(相当于java中的ifelse,switch case 控制语句),但是在学习的过程中遇到了一些问题.RouteOnAttr ...
- Linux扩展篇-shell编程(五)-流程控制(一)-if语句
基本语法: (1)单分支 if [ condition ];then statement(s) fi 或 if [ condition ] then statement(s) fi (2)多分支 if ...
- ColorEasyDuino上手指南
介绍 ColorEasyDuino是嘉立创推出的一块Aduino开发板(类似物),具有丰富的外设接口:uart.i2c.spi.adc.pwm等:开发板设计参考原型是Arduino Uno,采用的芯片 ...
- JavaScript:Function:函数(方法)对象
<!DOCTYPE html><html> <head> <meta charset="utf-8"> ...
- 牛客小白月赛96(待F)
比赛链接:牛客小白月赛96 赛时感受 赛时在前面卡的时间有点长,C题没开longlong wa了n发,D题没考虑负数又wa了n发,然后来写E的时候时间就不长了,匆忙写一次交一发. A 思路 当其中一个 ...
- Primer Premier 6安装使用教程
Primer Premier是一款专业级PCR引物设计工具软件,专为科研及分子生物学实验定制PCR扩增.测序探针及杂交引物.该程序运用尖端演算法评估引物的特异性.二聚体可能性和熔解温度等核心属性,确保 ...
- python安装pywifi
1.Windows安装: 在Dos窗口中输入以下命令: pip install pywifi 如果找不到pip命令,那么需要将Python安装文件夹下Scripts文件夹的绝对路径加入环境变量中. 2 ...
- SDL3 入门(3):三角形
SDL3 提供了 SDL_RenderGeometry 函数绘制几何图形,用法和 OpenGL 差不多,先定义顶点数据,然后根据顶点数据绘制几何图形. 绘制三角形的代码如下: std::array&l ...