首页  

scala 模式匹配     所属分类 scala 浏览量 502
scala 模式匹配 类似于Java中的switch
case分支顺序匹配  匹配成功则执行 匹配不成功,继续匹配
如果所有case都不匹配,执行case _分支,类似于Java switch 中 default语句


常量模式匹配 
类型匹配模式
case class模式
模式守卫  在模式后面加上if判断语句
Option匹配


package demo


case class Pet(id:Int,name:String){
}

object PatternMatchDemo {
  def main(args: Array[String]) {
    println(constantPatternMatch(3))
    println(constantPatternMatch(true))
    println(constantPatternMatch("test"))
    println(constantPatternMatch(null))
    println(constantPatternMatch(Nil))
    println(constantPatternMatch(9))

    println(typePatternMatch(3))
    println(typePatternMatch("hello"))
    println(typePatternMatch(3.3))
    println(typePatternMatch(null))

    val map = Map(("a", 1), ("b", 2))
    optionMatch(map,"a");
    optionMatch(map,"b");
    optionMatch(map,"c");

    val pet = new Pet(1,"cat")
    caseClassMatch(pet);
    caseClassMatch(1);

    println(abs(1));
    println(abs(0));
    println(abs(-1));

  }

  def constantPatternMatch(x: Any) = x match {
    case 3 => "int 3"
    case true => "bool true"
    case "test" => "string test"
    case null => "null"
    case Nil => "Nil empty list"
    case _ => "other"
  }

  def typePatternMatch(t: Any) = t match {
    case t: String => "String"
    case t: Int => "Integer"
    case t: Double => "Double"
    case _ => "Other Type"
  }

  def optionMatch(m: Map[String, Int],key: String) = m.get(key) match {
    case Some(x) => println(x)
    case None => println("notExist")
  }

  def caseClassMatch(x: Any) = x match {
    case Pet(id,name) => println(id+","+name)
    case _ => println("other")
  }

  def abs(num: Int): Int = {
    num match {
      case i if i >= 0 => i
      case i if i < 0 => -i
    }
  }

}

上一篇     下一篇
Scala object 伴生对象

Scala中apply的用法

大数据工程师入门概述

scala Option Some None

scala 类型系统

Scala 构造函数