由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的更多相关文章

  1. Scala学习文档-样本类与模式匹配(match,case,Option)

    样本类:添加了case的类便是样本类.这种修饰符可以让Scala编译器自动为这个类添加一些语法上的便捷设定. //样本类case class //层级包括一个抽象基类Expr和四个子类,每个代表一种表 ...

  2. scala里的模式匹配和Case Class

    模式匹配的简介 scala语言里的模式匹配可以看作是java语言中switch语句的改进. 模式匹配的类型 包括:常量模式.变量模式.构造器模式.序列模式.元组模式以及变量绑定模式等. 常量模式匹配 ...

  3. Scala中的match(模式匹配)

    文章来自:http://www.cnblogs.com/hark0623/p/4196261.html   转载请注明 代码如下: /** * 模式匹配 */ case class Class1(pa ...

  4. scala高级内容(一) Case Class

    一. 操作符 自定义操作符 操作付默认左结合调用.除了以:结尾的操作符是右结合调用 object OperaterTest extends App{ val a: myInt = new myInt( ...

  5. 聊聊 scala 的模式匹配

    一. scala 模式匹配(pattern matching) pattern matching 可以说是 scala 中十分强大的一个语言特性,当然这不是 scala 独有的,但这不妨碍它成为 sc ...

  6. 【scala】模式匹配

    Scala的模式匹配是通过match表达式从若干可选项中选择,类似Java中的switch. 例子: val firstArg = if(args.length>0) args(0) else ...

  7. Scala之模式匹配(Patterns Matching)

    前言 首先.我们要在一開始强调一件非常重要的事:Scala的模式匹配发生在但绝不仅限于发生在match case语句块中.这是Scala模式匹配之所以重要且实用的一个关键因素!我们会在文章的后半部分具 ...

  8. scala 常用模式匹配类型

    模式匹配的类型 包括: 常量模式 变量模式 构造器模式 序列模式 元组模式 变量绑定模式等. 常量模式匹配 常量模式匹配,就是在模式匹配中匹配常量 objectConstantPattern{ def ...

  9. Scala学习——模式匹配

    scala模式匹配 1.基础match case(类似java里switch case,但功能强大些) object MatchApp { def main(args: Array[String]): ...

  10. scala学习手记40 - case表达式里的模式变量和常量

    再来看一下之前的一段代码: def process(input: Any) { input match { case (a: Int, b: Int) => println("Proc ...

随机推荐

  1. umask永久修改用户创建文件权限

    Linux里永久设置用户创建文件权限的配置文件是/etc/profile.可以在该文件中添加umask命令来设置默认权限.具体操作步骤如下: 打开/etc/profile文件:sudo vi /etc ...

  2. C基本知识

    1 C基本数据类型 C基本的数据类型说明: 2 字节序 测试代码: #include <stdio.h> typedef unsigned char *byte_pointer; void ...

  3. ztree.js 禁止点击事件和鼠标禁用

    先看样式 var _t = this; var setting = { view: { fontCss: { color: "#5E5F61" }, showIcon: true, ...

  4. cors解决跨域 服务器代理方式

    // cors 方法         // 后端程序员通过定义后端程序,让跨域访问,可以正常执行,可以获取响应体内容         // 前端程序员不需要做任何的调整         // 后端程序 ...

  5. ABC353

    不知道为啥有断更了一周... E woc,怎么跟我出的题目这么像 先把字符串扔到一个 Trie 里面,然后对于每一个点我们考虑这一个点到根节点组成的字符串能是多少对字符串的最长公共前缀. 我们定义 \ ...

  6. .net core .net6 webapi 连接mysql 8

    1.表结构: CREATE TABLE `table2` ( `id` BIGINT NOT NULL AUTO_INCREMENT, `myname` varchar(255) NOT NULL, ...

  7. JVM垃圾回收器与调优参数

    引言 JVM为了更有效率的对堆空间进行垃圾回收,把堆空间进行了分代,分为年轻代.老年代和永久代(在1.8版本以后,永久代已经被彻底移除了,被元空间取而代之). 当一个对象出生时,会首先选择在eden区 ...

  8. C#.NET与JAVA互通之MD5哈希V2024

    C#.NET与JAVA互通之MD5哈希V2024 配套视频: 要点: 1.计算MD5时,SDK自带的计算哈希(ComputeHash)方法,输入输出参数都是byte数组.就涉及到字符串转byte数组转 ...

  9. AI赋能ITSM:企业运维跃迁之路

    随着企业信息化建设的深入,IT运维管理作为保证企业信息系统稳定运行的重要工作,越来越受到重视. 那么,什么是IT运维呢? 简单地说,IT运维是一系列维护.管理和优化企业IT基础设施.系统和应用程序的活 ...

  10. readhat8搭建SFTP双机高可用并配置Rsync数据实时同步

    环境准备: 主机 host-61-118 : 192.168.61.118 host-61-119:192.168.61.119 vip:192.168.61.220 检测openssh版本,版本必须 ...