Scala Match

来源:互联网 发布:软件设计师考试教程 编辑:程序博客网 时间:2024/05/18 01:44

Scala中的match类似与Java中的switch case结构。在理解match之前,记住scala中,几乎一切都是表达式。

匹配值

  val times = 1                                   //> times  : Int = 1  times match {     case 1 => "one"    case 2 => "two"    case _ => "some other number"  }                                               //> res0: String = one  val timeEnglish = times match {    case 1 => "one"    case 2 => "two"    case _ => "some other number"  }                                               //> timeEnglish  : String = one

可以看到,中间部分的times …其实是作为一个表达式存在的,因此我们可以把结果付给timeEnglish这个变量。其中下划线_表示其他未匹配的内容,类似与Java中的default。
我们也可以根据待匹配得知做条件判断:

times match {  case i if i == 1 => "one"  case i if i == 2 => "two"  case _ => "some other number"}

case后面先给待匹配的值取个别名,便于做条件判断。

匹配类型

除了根据值匹配外,还可以根据类型匹配:

def bigger(o: Any): Any = {  o match {    case i: Int if i < 0 => i - 1    case i: Int => i + 1    case d: Double if d < 0.0 => d - 0.1    case d: Double => d + 0.1    case text: String => text + "s"  }}

匹配类实例

def calcType(calc: Calculator) = calc match {  case _ if calc.brand == "hp" && calc.model == "20B" => "financial"  case _ if calc.brand == "hp" && calc.model == "48G" => "scientific"  case _ if calc.brand == "hp" && calc.model == "30B" => "business"  case _ => "unknown"}

这里的条件判断中直接使用待匹配的变量名calc。整个match表达式的值就作为方法的返回值。
但是这样比较很繁琐啊,因此scala提供了特殊的类叫case class,这类class专门为match case准备。

case class

使用关键字case 和class定义case类:

 case class Calculator(brand: String, model: String)

case类实例化的时候可以不用new关键字:

Calculator("Kosio" , "HH")       //> res0: test.Calculator = Calculator(Kosio,HH)

case类可以像正常类一样定义方法。

使用case class做match的时候,就很方便了:

val hp20b = Calculator("hp", "20B")val hp30b = Calculator("hp", "30B")def calcType(calc: Calculator) = calc match {  case Calculator("hp", "20B") => "financial"  case Calculator("hp", "48G") => "scientific"  case Calculator("hp", "30B") => "business"  case Calculator(ourBrand, ourModel) => "Calculator: %s %s is of unknown type".format(ourBrand, ourModel)}

最后偶一个case匹配前面都没有匹配到的情况,也可以这么写:

case Calculator(_, _) => "Calculator of unknown type"

甚至可以不关心他时不时Calculator:

 case _ => "Calculator of unknown type"

或者我们可以将匹配的值重新绑定到另一个名字:

case c@Calculator(_, _) => "Calculator: %s of unknown type".format(c)
0 0
原创粉丝点击