Scala模式匹配
来源:互联网 发布:淘宝里的视频怎么转发 编辑:程序博客网 时间:2024/06/08 03:07
object MatchDemo { /** * 定义偏函数用PartialFunction来表示 * PartialFunction[T1,T2],T1表示传入参数的数据类型,T2表示返回值的数据类型 * 偏函数体中的case只会执行一个,如果匹配到了就不会继续往下匹配 */ val func: PartialFunction[String, Int] = { case "a" => 1 case "b" => 2 case _ => -1 } /** * 匹配字符串 */ def matchString(str: String) = { str match { case "a" => 1 case "b" => 2 case _ => -1 } } /** * 匹配类型 */ def matchType(x: Any) = { x match { case x: String => println(x.getClass + " " + x) case x: Int if x > 5 => println(x) case _ => println("unknown") } } /** * 匹配数组 */ def matchArray(array: Array[Int]) = { array match { case Array(1, x, y) => println("匹配以1开头,有三个元素的数组") case Array(0) => println("匹配只有0这个元素的数组") case Array(0, _*) => println("匹配以0开头,任意多个元素的数组") case _ => println("unknown") } } /** * 匹配序列List * Nil是一个空的List,定义为List[Nothing] */ def matchList(list: List[Int]) = { list match { case 5 :: Nil => println("匹配只有5这个元素的序列") case x :: y :: Nil => println("匹配只有两个元素的序列") case x :: tail => println("匹配有任意多个元素的序列") case _ => println("unknown") } } /** * 匹配元组 */ def matchTuple(tuple:Any) = { tuple match { case (x, y, 6) => println("匹配只有三个元素并且以6结尾的元组") case (1, x, y) => println("匹配以1开头有三个元素的元组") case _ => println("unknown") } } def main(args: Array[String]): Unit = { val test = func("a") println(test) println(matchString("b")) matchType("你好") matchType(3) matchType(6) matchType(1.5) println("============================") matchArray(Array(1, 2, 3)) matchArray(Array(0)) matchArray(Array(0, 1, 2, 3)) matchArray(Array(1, 2)) println("=========================") matchList(List(5, 6, 7)) println("=========================") matchTuple((1,2,6)) }}
阅读全文
0 0
- scala 正则匹配(模式匹配)
- scala简要:模式匹配
- Scala模式匹配
- Scala 模式匹配
- Scala中的模式匹配
- scala 模式匹配
- Scala之模式匹配
- Scala的模式匹配
- Scala模式匹配
- scala的模式匹配
- Scala 之 模式匹配
- Scala之模式匹配
- scala模式匹配·
- Scala模式匹配
- Scala模式匹配
- scala模式匹配
- scala基础-模式匹配
- Scala模式匹配
- jvm学习笔记--运行时数据区域
- 学习机器学习之如何根据需求选择一种算法
- 477. Total Hamming Distance(C++)
- SpringCloud(第 049 篇)Netflix Eureka 源码深入剖析(上)
- Leetcode 712. Minimum ASCII Delete Sum for Two Strings
- Scala模式匹配
- 动态规划 背包问题
- 然而沼跃鱼早就看穿了一切
- c语言获取目录下的所有文件名
- 【Python】Python的类、对象、属性、方法
- NOIP模拟10.22
- 大数据学习23:hadoop-2.6.0-cdh5.7.0 编译,支持 native 和 snappy
- Ionic 简易侧拉框
- Photoshop——APP设计规范