您的位置:首页 > 其它

模式匹配基本语法与在集合中的使用

2016-03-20 12:57 483 查看
场景
模式匹配基本语法与在集合中的使用
实验
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 深入浅出实战经典 . 王家林模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: