栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

大数据之Scala 模式匹配 完整使用(第八章)

大数据之Scala 模式匹配 完整使用(第八章)

大数据之Scala 模式匹配 完整使用

一、基本语法

1、实操2、说明 二、匹配常量

1)说明2)实操 三、匹配类型

1)说明2)案例实操

一、基本语法

模式匹配语法中,采用 match 关键字声明,每个分支采用 case 关键字进行声明,当需
要匹配时,会从第一个 case 分支开始,如果匹配成功,那么执行对应的逻辑代码,如果匹配不成功,继续执行下一个分支进行判断。如果所有 case 都不匹配,那么会执行 case _分支,类似于 Java 中 default 语句

1、实操
package chapter08

object Test01_PatternMatchbase {
  def main(args: Array[String]): Unit = {
    //1、基本定义语法
    val x: Int = 2
    val y: String = x match {
      case 1 => "one"
      case 2 => "two"
      case 3 => "three"
      case _ => "other"
    }
    println(y)

    //2、实例:用模式匹配实现简单二元运算
    val a = 25
    val b = 13

    def matchDualOp(op: Char) = op match {
      case '+' => a + b
      case '-' => a - b
      case '*' => a * b
      case '/' => a / b
      case _ => -1

      //如果一个引用类型、和值类型肯定返回值为Any
    }

    println(matchDualOp('+'))
    println(matchDualOp('/'))
    println(matchDualOp('\'))

    def getCount(op: String) =op match {
      case "+" => a + b
      case _=> -2
    }
    println(getCount("+"))

  }
}

2、说明

(1)如果所有 case 都不匹配,那么会执行 case _ 分支,类似于 Java 中 default 语句,
若此时没有 case _ 分支,那么会抛出 MatchError。
(2)每个 case 中,不需要使用 break 语句,自动中断 case。
(3)match case 语句可以匹配任何类型,而不只是字面量。
(4)=> 后面的代码块,直到下一个 case 语句之前的代码是作为一个整体执行,可以
使用{}括起来,也可以不括。

二、匹配常量 1)说明

Scala 中,模式匹配可以匹配所有的字面量,包括字符串,字符,数字,布尔值等等。

2)实操
    def describeConst(x: Any): String = x match {
      case 1 => "Int One"
      case "hello" => "String hello"
      case true => "Boolean True"
      case '+' => "Char +"
      case abc => ""
    }

    println(describeConst("hello"))
    println(describeConst('+'))
    println(describeConst(0.3))
三、匹配类型 1)说明

需要进行类型判断时,可以使用前文所学的 isInstanceOf[T]和 asInstanceOf[T],也可使
用模式匹配实现同样的功能。

2)案例实操
 //匹配类型
    def describeType(x: Any): String = x match {
      case i: Int => "Int " + i
      case s: String => "String " + s
      case list: List[String] => "List " + list
      case array: Array[Int] => "Array[Int] " + array.mkString(",")
      case a => "Something else: " + a
    }
    println(describeType(35))
    println(describeType("hello"))
    println(describeType(List("hi", "hello")))
    println(describeType(List(2, 23)))
    println(describeType(Array("hi", "hello")))
    println(describeType(Array(2, 23)))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/745183.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号