前言
Scala 提供了强大的模式匹配机制,应用也非常广泛。
一个模式匹配包含了一系列备选项,每个都开始于关键字 case。每个备选项都包含了一个模式及一到多个表达式。箭头符号 => 隔开了模式和表达式。
内容匹配
e.g.
//内容匹配:字符串:正则
//这里先确定邮箱格式正确之后再确认邮箱类型
val email = "796282767@qq.com"
val rst = email match {
case i if (i.matches("^\\w+@[0-9a-z]{2,10}\\.(com|qq|edu|org)$")) => i match {
case i if (i.matches(".*@qq\\..*")) => Some("qq")
case i if (i.matches(".*@163\\..*")) => Some("163")
case i if (i.matches(".*@hotmail\\..*")) => Some("hotmail")
}
case i => None
}
println(rst)
e.g. result:
Some(qq)
类型匹配
e.g.
("a", true, 18, 20.22, 'b', 20L, 20.1f).productIterator.foreach(x => println(x match {
case i: String => s"$i is a String"
case i: Boolean => s"$i is a Boolean"
case i: Int => s"$i is a Int"
case i: Double => s"$i is a Double"
case i: Char => s"$i is a Char"
case i: Long => s"$i is a Long"
case i: Float => s"$i is a Float"
}))
e.g.result:
a is a String
true is a Boolean
18 is a Int
20.22 is a Double
b is a Char
20 is a Long
20.1 is a Float
结构匹配
e.g.
val products = Array((1, 2, 3), (1, (2, 3)), ((1, 2), 3))
products.foreach(x => println(x match {
case (a, b, c) => 'A'
case ((a, b), c) => 'B'
case (a, (b, c)) => 'C'
}))
e.g.result:
A
C
B
内容匹配:数值区间
e.g.
var age = 20;
val unit = age match {
case i if (i >= 18) => "mature"
case i => "raw"
}
println(unit)
e.g.result:
mature
原创作者:wsjslient |