模式匹配基本语法与在集合中的使用
2016-03-20 12:57
483 查看
场景
模式匹配基本语法与在集合中的使用
实验
参考文献
scala 深入浅出实战经典 . 王家林模式
模式匹配基本语法与在集合中的使用
实验
package com.scode.scala /** * author: Ivy Peng * function: 1、学习模式匹配 基本语法与在集合中的使用 * 2、了解提取器Extractor工作机制(待进一步理解) * date:2016/03/20 11.47 * sum: * 模式匹配语法:varName match * { * case matchContent => ops * ... * case * } * 1、可以把匹配的内容赋值给 matchContent,然后在 ops中对其进行操作 * 2、case分支不需要以 break结尾 */ object MatchOps { def main(args:Array[String])= { matchBase match_typeList(List(1,2)) match_tuple((0,3)) val pattern = "([0-9]+) ([a-z]+)".r "2016032 nice" match { case pattern(num,item)=> println(num+":"+item) } } def matchBase() { val data = 2 data match { case 1=> println("First") case 2=> println("Second") case _ => println("Unknow input") } //把匹配的内容,传递给 val i,在 => 后面可以使用 i val result = data match { case i if i==1 => "First" case num if num==2 => "Second" case _=> println("Unknow input") } println(result) "Spark".foreach { x => print( x match { case ' ' => "space" case ch => ch } ) } } def match_type(typ:Any)=typ match { case p:Int => println("Integer") case str:String => println("String") case m:Map[_,_] => m.foreach(println) case Array(0) => println("Array"+"0") case Array(x,y) => println("Array"+x+y) case Array(0,_*)=> println("Array"+"...") case _=> println("something else") } def match_typeList(t:Any)= t match { case 0::Nil => println("List:"+"0") case x::y::Nil=> println("List:"+x+y) case 0::tail=> println("List:"+"0 ...") case _=> println("Something else") } def match_tuple(tuple:Any)= tuple match { case (0,_)=> println("tuple:"+ "0") case (_,2)=> println(". 2") } }
参考文献
scala 深入浅出实战经典 . 王家林模式
相关文章推荐
- linux 扫描端口
- 还在抱怨JS文件里没有智能提示吗, VS10以及以上都可以 .NET
- rpm包管理功能全解
- ios后台程序持续运行方法
- lintcode-medium-Divide Two Integers
- 4000 基于DES加密的TCP聊天程序
- 【WebService开发】之编写天气预报的WebService客户端
- 求字符串长度
- FTP协议学习总结
- 软件项目管理的理解
- appcompat_v7/res/values-v21/themes_base.xml No resource found that matches the given name: androidXX
- 二进制与地址计算
- case class与case object实战
- 多线程“基础篇”11之 生产消费者问题
- 你该知道的json解析
- Problem F: 删出多余的空格
- progressBar和Handler实现进度条的加载 和RatingBar评分控件
- 在非root环境下安装某ss软件
- MySQL 查看约束,添加约束,删除约束 添加列,修改列,删除列
- UESTC 1034 AC Milan VS Juventus 分情况讨论