Pattern matching in Section 3 Scala: 1 - 5

7. The pattern matching and Sample Class

Scala has a very powerful pattern-matching mechanism, it can be applied to many occasions: as a switch statement, the type of inspection. And Scala also provides sample classes, pattern matching is optimized, can be quickly matched.

7.1. Matching string

Package cn.itcast.cases 
Import scala.util.Random Object CaseDemo01 the extends the App { Val ARR = the Array ( "Hadoop" , "ZooKeeper" , "Spark" ) Val name = ARR (Random.nextInt ( ARR .length)) name match { Case "Hadoop"    => the println ( " big data storage and distributed computing frameworks ..." ) Case "ZooKeeper" => the println ( " big data distributed coordination service framework ...")


 
 
 
   
   
    Case "the Spark" => println ( " big data distributed memory computing framework ..." ) 
    Case _ => println ( " I do not know you ..." )
  }
}
 

 

7.2. Match Type

package cn.itcast.cases
import scala.util.Random

object CaseDemo01 extends App{
 
val arr = Array("hello", 1, 2.0, CaseDemo)
  val v = arr(Random.nextInt(4))
  println(v)
  v match {
    case x: Int => println("Int " + x)
    case y: Double if(y >= 0) => println("Double "+ y)
    case z: String => println("String " + z)
    case _ => throw new Exception("not match exception")
  }
}
 

注意case y: Double if(y >= 0) => ...

When pattern matching can also add a guard condition. If you do not meet the conditions of the guards, will fall into the case _ in.

7.3. Matching array tuple, set,

package cn.itcast.cases

object CaseDemo03 extends App{

  val arr = Array(1, 3, 5)
  arr match {
    case Array(1, x, y) => println(x + " " + y)
    case Array(0) => println("only 0")
    case Array(0, _*) => println("0 ...")
    case _ => println("something else")
  }

  val lst = List(3, -1)
  lst match {
    case 0 :: Nil => println("only 0")
    case x :: y :: Nil => println(s"x: $x y: $y")
    case 0 :: tail => println("0 ...")
    case _ => println("something else")
  }

  val tup = (1, 3, 7)
  tup match {
    case (1, x, y) => println(s"1, $x , $y")
    case (_, z, 5) => println(z)
    case  _ => println("else")
  }
}
 

注意:在Scala中列表要么为空(Nil表示空列表)要么是一个head元素加上一个tail列表。

9 :: List(5, 2)  :: 操作符是将给定的头和尾创建一个新的列表

注意::: 操作符是右结合的,如9 :: 5 :: 2 :: Nil相当于 9 :: (5 :: (2 :: Nil))

7.4.   样例类

在Scala中样例类是一种特殊的类,可用于模式匹配。

定义形式:

case class 类型,是多例的,后面要跟构造参数。 case class Student(name:String)

case object 类型,是单例的。        case object Person

 

package cn.itcast.cases
import scala.util.Random

case class SubmitTask(id: String, name: String)
case class HeartBeat(time: Long)
case object CheckTimeOutTask

object CaseDemo04 extends App{
  val arr = Array(CheckTimeOutTask, HeartBeat(12333), SubmitTask("0001", "task-0001"))

  arr(Random.nextInt(arr.length)) match {
    case SubmitTask(id, name) => {
      println(s"$id, $name")
    }
    case HeartBeat(time) => {
      println(time)
    }
    case CheckTimeOutTask => {
      println("check")
    }
  }
}
 

7.5.   Option类型

在Scala中Option类型用样例类来表示可能存在或者可能不存在的值(Option的子类有Some和None)。Some包装了某个值,None表示没有值

 

package cn.itcast.cases

object OptionDemo {
  def main(args: Array[String]) {
    val map = Map("a" -> 1, "b" -> 2)
    val v = map.get("b") match {
      case Some(i) => i
      case None => 0
    }
    println(v)
    //更好的方式
   
val v1 = map.getOrElse("c", 0)
    println(v1)
  }
}
 

7.6.   偏函数

被包在花括号内没有match的一组case语句是一个偏函数,它是PartialFunction[A, B]的一个实例,A代表输入参数类型,B代表返回结果类型,常用作输入模式匹配,偏函数最大的特点就是它只接受和处理其参数定义域的一个子集。

package cn.itcast.cases

object PartialFuncDemo  {

  valfunc1: PartialFunction[String, Int] = {
    case "one" => 1
    case "two" => 2
    case _ => -1
  }

  def func2(num: String) : Int = num match {
    case "one" => 1
    case "two" => 2
    case _ => -1
  }

  def main(args: Array[String]) {
    println(func1("one"))
    println(func2("one"))
  }
}

Guess you like

Origin www.cnblogs.com/mediocreWorld/p/11373023.html