Scala Pattern Matching

本文介绍了Scala中的模式匹配概念,包括基于值、类型及case类的模式匹配应用实例。通过具体的代码示例,展示了如何根据不同条件返回不同的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创转载请注明出处:http://agilestyle.iteye.com/blog/2333026

 

 

基于值的模式匹配 

A match expression compares a value against a selection of possibilities. All match expressions begin with the value you want to compare, followed by the keyword match, an opening curly brace, and then a set of possible matches and their associated actions, and ends with a closing curly brace. Each possible match and its associated action begins with the keyword case followed by an expression. The expression is evaluated and compared to the target value. If it matches, the expression to the right of the => (“rocket”) produces the result of the match expression.

package org.fool.scala.basic

object ScalaMatchExpressions extends App {
  def matchColor(color: String): String = {
    color match {
      case "red" => "RED"
      case "blue" => "BLUE"
      case "green" => "GREEN"
      case _ => "UNKNOWN COLOR: " + color
    }
  }

  println(matchColor("red"))
  println(matchColor("white"))
}

Console Output


  

基于类型的模式匹配

参数类型Any允许任何类型的参数。如果向某个方法传递的类型具有多样性,并且他们没有任何共性成分,那么Any就可以解决此问题。下划线的作用是通配符,用来匹配任何与前面的值不匹配的对象。

package org.fool.scala.basic

case class Person(name: String)

object ScalaPatternMatchingWithTypes extends App {
  def acceptAnything(x: Any): String = {
    x match {
      case s: String => "A String: " + s
      case i: Int if (i < 20) => s"An Int Less than 20: $i"
      case i: Int => s"Some Other Int: $i"
      case p: Person => s"A person ${p.name}"
      case _ => "I have no fucking idea!"
    }
  }

  println(acceptAnything(5))
  println(acceptAnything(25))
  println(acceptAnything("Hello World"))

  val p = Person("Kobe")
  println(acceptAnything(p))

  println(acceptAnything(Vector(1, 2, 3)))
}

Console Output


 

基于case类的模式匹配

package org.fool.scala.basic

case class Passenger(first: String, last: String)

case class Train(travelers: Vector[Passenger], line: String)

case class Bus(passengers: Vector[Passenger], capacity: Int)

object PatternMatchingCaseClasses extends App {
  def travel(transport: Any): String = {
    transport match {
      case Train(travelers, line) =>
        s"Train line $line $travelers"
      case Bus(travelers, seats) =>
        s"Bus size $seats $travelers"
      case Passenger => "Walking along"
      case what => s"$what is in limbo!"
    }
  }

  val travellers = Vector(
    Passenger("Kobe", "Bryant"),
    Passenger("Michael", "Jordan")
  )

  val trip = Vector(
    Train(travellers, "CRH Train"),
    Bus(travellers, 100)
  )

  println(travel(trip(0)))
  println(travel(trip(1)))

}

Note:

没有任何类型的标识符(what),表示它会匹配上面各个case表达式未匹配的任何其他事物。

Console Output


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值