Scala模式匹配

Scala模式匹配

  • match语句
  • case类

模式匹配的实例(Char):

import scala.io.StdIn._
object TestMatch {
  def main(args: Array[String]): Unit = {
    println("Please input the score:")
    val grade=readChar()
    grade match {
      case'A'=>println("85-100")
      case'B'=>println("70-84")
      case'C'=>println("60-69")
      case'D'=>println("<60")
      case _=>println("error input!")
    }
  }
}

模式匹配的实例(Line):

import scala.io.StdIn.readChar
object TestMatch2 {
  def main(args: Array[String]): Unit = {
    println("Please input the score:")
    val country=readLine()
    country match {
      case "China"=>println("中国")
      case "America"=>println("美国")
      case "Japan"=>println("日本")
      case _=>println("我不认识!")
    }
  }
}

模式匹配的实例(所有值匹配):

object TestMatch3 {
  def main(args: Array[String]): Unit = {
    for (elem <- List(6, 9, 0.618, "Spark", "Hadoop", 'Hello)) {
      val str = elem match {
        case i: Int => i + "is an int value." //匹配整形的值,并赋值给i
        case d: Double => d + "is a double value." //匹配浮点型的值
        case "Spark" => "Spark is found." //匹配特定的字符串
        case s: String => s + "is a string value." //匹配其它字符串
        case _ => "unexpected value: " + elem //与以上都不匹配
      }
      println(str)
    }
  }
}

out:

6is an int value.
9is an int value.
0.618is a double value.
Spark is found.
Hadoopis a string value.
unexpected value: 'Hello

match语句支持case中添加守卫(guard):

object TestMatch4 {
  def main(args: Array[String]): Unit = {
    for (elem <- List(1, 2, 3, 4)) {
      elem match {
        case _ if (elem % 2 == 0) => println(elem + " is even.")
        case _ => println(elem + " is odd.")
      }
    }
  }
}

out:

1 is odd.
2 is even.
3 is odd.
4 is even.

apply和unapply自动生成调用:

case class Car5(brand: String, price: Int)
object Car5_t {
  def main(args: Array[String]): Unit = {
    val myBYDCar = Car5("BYD", 89000)
    val myBMWCar = Car5("BMW", 1200000)
    val myBenzCar = Car5("Benz", 1500000)
    for (car <- List(myBYDCar, myBMWCar, myBenzCar)) {
      car match {
        case Car5("BYD", 89000) => println("Hello,BYD!")
        case Car5("BMW", 1200000) => println("Hello,BMW!")
        case Car5(brand, price) => println("Brand:" + brand + ",Price:" + price + ",do you want it?")
      }
    }
  }
}

out:

Hello,BYD!
Hello,BMW!
Brand:Benz,Price:1500000,do you want it?

以上代码相当于自动生成了如下内容

  def apply(brand: String, price: Int) = new Car5(brand, price)
  def unapply(c: Car5): Option[(String, Int)] = Some((c.brand, c.price))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值