当前位置:网站首页>Scala-day06- pattern matching - Generic

Scala-day06- pattern matching - Generic

2022-06-26 12:09:00 There will always be daylight

One : Basic grammar

package chapter07

object Test01_PatternMatchBase {
  def main(args: Array[String]): Unit = {
    //1. Basic definition syntax 
    val x:Int = 2
    val y:String = x match {
      case 1 => "one"
      case 2 => "two"
      case 3 => "three"
      case _ => "other"
    }
    println(y)// according to x Value , Output y Value , This case will be output two

    //2. Example : Using pattern matching to realize simple binary operation 
    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 '%' => a % b
      case _ => -1
    }
    println(matchDualOp('+'))

    //3. Mode guard 
    // Find the absolute value of an integer 
    def abs(num:Int):Int = {
      num match {
        case i if i>= 0 => i
        case i if i<0 => -i
      }
    }

    println(abs(67))
  }
}

Two : Match constants - Match type 、 Array 、 list 、 Tuples

package chapter07

object Test02_MatchTypes {
  def main(args: Array[String]): Unit = {
    //1. Match constants 
    def describeConst(x:Any):String = x match {
      case 1 => "Int one"
      case "hello" => "String hello"
      case true => "Boolean true"
      case '+' => "Char +"
      case _ => ""
    }

    println(describeConst("hello"))

    //2. Match type 
    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(describeConst(35))

    //3. The match array 
    for (arr <- List(
      Array(0),
      Array(1,0),
      Array(0,1,0),
      Array(1,1,0),
      Array(2,3,7,15),
      Array("hello",20,30)
    )){
      val result = arr match {
        case Array(0) => "0"
        case Array(1,0) => "Array(1,0)"
        case Array(x,y) => "Array:" + x + "," + y
        case Array(0,_*) => " With 0 The first array "
        case Array(x,1,z) => " In the middle 1 A three element array of "
        case _ => "something else"
      }
      println(result)
    }

    //4. Match list -- Mode one 
    for(list <- List(
      List(0),
      List(1,0),
      List(0,0,0),
      List(1,1,0),
      List(88),
    )){
      val result = list match {
        case List(0) => "0"
        case List(x,y) => "List(x,y):" + x + "," + y
        case List(0,_*) => "List(0....)"
        case List(a) => "List(a):" + a
        case _ => "something else"
      }
      println(result)
    }

    //4. Match list -- Mode two 
    val list = List(1,2,5,7,24)
    val result = list match {
      case first::second::rest => println(s"first:$first,second:$second,rest:$rest")
      case _ => println("something else")
    }
    println(result)

    //5. Match tuples 
    for(tuple <- List(
      (0,1),
      (0,0),
      (0,1,0),
      (0,1,1),
      (1,23,56),
      ("hello",true,0.5),
    )){
      val result = tuple match {
        case (a,b) => "" + a + "," + b
        case (0,_) => "(0,_)"
        case (a,1,_) => "(a,1,_)" + a
        case _ => println("something else")
      }
      println(result)
    }
  }
}


package chapter07

object Test03_MatchTupleExtend {
  def main(args: Array[String]): Unit = {
    //1. Match... When declaring variables 
    val (x,y) = (10,"hello")
    println(s"x:$x,y:$y")

    val List(first,second,_*) = List(23,15,9,78)

    val fir::sec::rest = List(23,15,9,18)
    println(s"first:$fir,second:$sec,res:$rest")

    //for Derivation for pattern matching 
    val list:List[(String,Int)] = List(("a",12),("b",35),("c",27))
    for (elem <- list){
      println(elem._1 + " " +elem._2)
    }

    // take list Elements are directly defined as tuples , Assign a value to a variable 
    for((word,count) <- list){
      println(word + " " + count)
    }

    // You can ignore variables at a certain location , Just traverse key perhaps value
    for((word,_) <- list){
      println(word)
    }

    // You can specify how many values a location must have 
    for(("a",count) <- list){
      println(count)
    }
  }
}

3、 ... and : Matching objects and sample classes

package chapter07

object Test_MatchObject {
  def main(args: Array[String]): Unit = {
    val student = new Student("alice",18)

    // Match the content of the object instance 
    val result = student match {
      case Student("alice",18) => "Alice,18"
      case _=> "Else"
    }
    println(result)
  }
}

// Defining classes 
class Student(val name:String,val age:Int)

// Define accompanying objects 
object Student{
  def apply(name: String, age: Int): Student = new Student(name, age)
  // Must be realized unapply Method , Used to disassemble object properties 
  def unapply(student: Student): Option[(String, Int)] = {
    if(student == null){
      None
    }else{
      Some((student.name,student.age))
    }
  }
}

package chapter07

object Test05_MatchCaseClass {
  def main(args: Array[String]): Unit = {
    val student =  Student("alice",18)

    // Match the content of the object instance 
    val result = student match {
      case Student("alice",18) => "Alice,18"
      case _=> "Else"
    }
    println(result)
  }
}


// Define the sample class 
case class Student(val name:String,val age:Int)

Four : Exception handling mechanism

package chapter08

object Test01_Exception {
  def main(args: Array[String]): Unit = {
    try{
      val n = 10 / 0
    }catch {
      case e:ArithmeticException => {
        println(" Arithmetic exception occurred ")
      }
      case e:Exception => {
        println(" A general exception occurred ")
      }
    }finally {
      println(" End of processing ")
    }
  }
}

5、 ... and : Implicit conversion - Implicit parameter - Implicit value - Implicit functions

package chapter08

object Test02_Implcit {
  def main(args: Array[String]): Unit = {
    // Implicit functions 
    implicit def convert(num:Int):MyRichInt = new MyRichInt(num)

    println(12.myMax(15))

    // Implicit class 

    implicit class MyRichInt(val self:Int){
      // Customize the size comparison method 
      def myMax(n:Int):Int = if (n < self) self else n
      def myMin(n:Int):Int = if (n < self) n else self
    }

    println(12.myMin(2))

    // Implicit parameter , The same scope , There can only be one of the same type , Implicit values override default values 
    implicit val str:String = "alice"
    def sayHello(implicit name:String):Unit ={
      println("hello," + name)
    }
    sayHello

  }
}

/*
// Custom class 
class MyRichInt(val self:Int){
  // Customize the size comparison method 
  def myMax(n:Int):Int = if (n < self) self else n
  def myMin(n:Int):Int = if (n < self) n else self
}*/

6、 ... and : Generic - Covariant and contravariant

package chapter08

object Test03_Generics {
  def main(args: Array[String]): Unit = {
    // Covariant and contravariant 
    val child:Parent = new Child
    val childList:MyCollecion[Parent] = new MyCollecion[Child]
  }
}

// Define inheritance 
class Parent{}

class Child extends Parent{}

class SubChild extends Child{}

// Define collection types for generics 
class MyCollecion[E]{}

7、 ... and : Upper and lower bounds of generics

Class PersonList[T<:Person]{    // The upper limit of generics 
}

Class PersonList[T>:Person]{    // The lower bound of generics 
}

 

原网站

版权声明
本文为[There will always be daylight]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170527108009.html