【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 ...
随机推荐
- Yolov8和Yolov10的差异以及后处理实现
Yolo模型可分为4个维度的概念 模型版本.数据集.模型变体(Variants).动态/静态模型. Yolo各模型版本进展历史 Yolov(2015年华盛顿大学的 Joseph Redmon 和 Al ...
- 剑指Offer-67.剪绳子(C++/Java)
题目: 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m.n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],...,k[m].请问k[0]xk[1]x...xk[m ...
- 三维API sheder 基础
这个shader 是靠三维数学 影响 二维像素 导致像素颜色改变 它是每个像素走一遍脚本算法 写的时候注意 语言格式 写错了 shader脚本是不能用的,根本就不好使这个 可以用区域 用xyz y为0 ...
- JAVA IDEA Maven 加速镜像 阿里云
JAVA IDEA Maven 加速镜像 阿里云 如果是IDEA自带的则在: C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 20 ...
- 暴走漫画系列之高仿淘宝收货地址(附demo)
引语: 我是个程序猿,一天我坐在路边一边喝水一边苦苦检查bug. 这时一个乞丐在我边上坐下了,开始要饭,我觉得可怜,就给了他1块钱. 然后接着调试程序.他可能生意不好,就无聊的看看我在干什么,然后过了 ...
- JAVA发送邮件报错: 535 Error: authentication failed, system busy。
解决方法: 1.设置 -> 微信绑定 -> 开启安全登录 -> 生成新密码 2.使用生成的新密码替换邮箱登录密
- Shiro 的优点
a.简单的身份认证, 支持多种数据源 b.对角色的简单的授权, 支持细粒度的授权(方法级) c.支持一级缓存,以提升应用程序的性能 d.内置的基于 POJO 企业会话管理, 适用于 Web 以及非 W ...
- 关于编译告警 C4819 的完整解决方案 - The file contains a character that cannot be represented in the current code page (number). Save the file in Unicode format to prevent data loss.
引言 今天迁移开发环境的时候遇到一个问题,同样的操作系统和 Visual Studio 版本,原始开发环境一切正常,但是迁移后 VS 出现了 C4819 告警,上网查了中文的一些博客,大部分涵盖几种解 ...
- 洛谷 P4343 自动刷题机
题目链接:自动刷题机 思路 二分典题,两个二分判断出可能的最大值和最小值.需要注意当删掉y行代码后,当前代码行数小于0时需要将代码行数重新赋值为0,然后需要注意二分的n最大值的边界,因为x[i]的最大 ...
- 用基础Array数组实现动态数组、链表、栈和队列
代码地址: https://gitee.com/Tom-shushu/Algorithm-and-Data-Structure.git 一.ArrayList自定义封装 package com.zho ...