scala match匹配
程序员文章站
2022-06-14 17:14:55
...
match 常用类型匹配
object TestMatch {
def main(args: Array[String]): Unit = {
matchAny("a")
matchArray()
matchTuple()
caseClassMacth()
matchEnum()
}
def matchAny(x:Any): Unit ={
// 用 match 来替代 isInstanceOf 和 asInstanceOf
/*
if(ch.isInstanceOf[Char]){
val c = ch.asInstanceOf[Char]
}*/
val result = x match{
case x:String => "space"
case x:Char => x
case _ => 0
}
println(result)
}
// 匹配数组
def matchArray(): Unit ={
val arr = Array[Int](0,5,1)
arr match {
case Array(x,y) => println(s"x=$x \t y=$y")
case Array(0,_*) => println("0,_*")
case _ => println("error")
}
}
// 匹配 元组
def matchTuple(): Unit ={
val tuple = new Tuple2("aa","bb")
println(tuple._1)
// 常用 下面这种方式
val (spring,summer,autumn,winter) = ("a","b","c","d")
println(spring)
}
// caseClass
def caseClassMacth(): Unit ={
abstract class Expr
case class Var(name:String) extends Expr
case class Number(num:Double) extends Expr
case class UnOp(operator : String , arg : Expr) extends Expr
case class BinOp(operator : String , left : Expr , right : Expr) extends Expr
def simplifyTop(expr : Expr) : Expr = expr match{
case UnOp("-" , UnOp("-" , e)) => e
case BinOp("+" , e , Number(0)) => e
case BinOp("*" , e , Number(1)) => e
case _ => expr
}
println(simplifyTop(BinOp("+",Number(num = 2),Number(num = 0))))
}
//模拟枚举 enum
def matchEnum(): Unit ={
//sealed 结合 case class 方式 定义枚举 sealed密封 关键字修饰
sealed abstract class TrafficLight // 父类
// red yellow green 子类
case class RED(stop:String) extends TrafficLight
case class YELLOW(warning:String) extends TrafficLight
case class GREEN(go:String) extends TrafficLight
val light:TrafficLight= RED(" stop")
light match {
case RED(stop) => println(stop)
case YELLOW(stop) => println(YELLOW)
case GREEN(stop) => println(GREEN)
}
//extends Enumeration 方式 定义枚举
class Season extends Enumeration{
val SPRITNG,SUMMER,AUtUMN,WINTER = Value // 大写 不是values
}
val season = new Season
println(season.SPRITNG)
}
}
推荐阅读
-
ThinkPHP like模糊查询,like多匹配查询,between查询,in查询,一般查询书写方法
-
python正则表达式match和search用法实例
-
解决打印机怪异提示之打印端口不匹配
-
PHP 正则匹配h1的数据报错 preg_match(): Unknown modifier 'h' in
-
php用正则表达式匹配中文实例详解
-
使用css3匹配手机屏幕横竖状态
-
针对搜索引擎的关键词匹配规则分析
-
node.js + socket.io 实现点对点随机匹配聊天
-
mybatis_ The content of element type association must match (constructor,id,result,ass ociation,collection,discriminator)
-
Linux常用基本命令:grep-从文件或者管道中筛选匹配的行