Scalaパターンマッチングケースの使用

基本的な文法

val num1 = 10
val num2 = 20
val option = '&'

// 模式匹配
val res: Any = option match {
    
    
  case '+' => num1 + num2
  case '-' => num1 - num2
  case '*' => num1 * num2
  case '/' => num1 / num2
  case _ => "运算符不合法"
}
println(res)

説明

  • すべてのケースが一致しない場合、Javaのデフォルトステートメントと同様に、case _ブランチが実行されます。この時点でcase_ブランチがない場合、MatchErrorがスローされます。
  • いずれの場合も、breakステートメントを使用する必要はなく、ケースは自動的に中断されます。
  • match caseステートメントは、リテラルだけでなく、任意のタイプに一致できます。
  • =>次のコードブロック(次のcaseステートメントが全体として実行される前のコード)は、{}で囲むことも、囲まないこともできます。

モードガード

  • ケース条件は、判断条件も指定します。
val num3 = -10
// 模式守卫
def myAbs(num: Int) = num3 match {
    
    
  case i:Int if i >= 0 => i
  case j:Int if j < 0 => -j
}

println(myAbs(num3))

一致定数

def main(args: Array[String]): Unit = {
    
    

    println(describe(6))

}

def describe(x: Any) = x match {
    
    
    case 5 => "Int five"
    case "hello" => "String hello"
    case true => "Boolean true"
    case '+' => "Char +"
}

マッチタイプ

def describe(x: Any) = x match {
    
    
    case i: Int => "Int"
    case s: String => "String hello"
    case m: List[_] => "List"
    case c: Array[Int] => "Array[Int]"
    case someThing => "something else " + someThing
}

def main(args: Array[String]): Unit = {
    
    
    //泛型擦除
    println(describe(List(1, 2, 3, 4, 5)))

    //数组例外,可保留泛型
    println(describe(Array(1, 2, 3, 4, 5, 6)))
    println(describe(Array("abc")))
}

配列を一致させる

def main(args: Array[String]): Unit = {
    
    
    for (arr <- Array(Array(0), Array(1, 0), Array(0, 1, 0), Array(1, 1, 0), Array(1, 1, 0, 1), Array("hello", 90))) {
    
     // 对一个数组集合进行遍历

        val result = arr match {
    
    
            case Array(0) => "0" //匹配Array(0) 这个数组
            case Array(x, y) => x + "," + y //匹配有两个元素的数组,然后将将元素值赋给对应的x,y
            case Array(0, _*) => "以0开头的数组" //匹配以0开头的数组
            case _ => "something else"
        }

        println("result = " + result)
    }
}

マッチリスト

for (list <- Array(List(0), List(1, 0), List(0, 0, 0), List(1, 0, 0), List(88))) {
    
    

    val result = list match {
    
    

        case List(0) => "0" //匹配List(0)
        case List(x, y) => x + "," + y //匹配有两个元素的List
        case List(0, _*) => "0 ..."
        case _ => "something else"
    }

    println(result)
}

val list: List[Int] = List(1, 2, 5, 6, 7)

list match {
    
    
    case first :: second :: rest => println(first + "-" + second + "-" + rest)
    case _ => println("something else")
}


マッチングタプル

 //对一个元组集合进行遍历
for (tuple <- Array((0, 1), (1, 0), (1, 1), (1, 0, 2))) {
    
    

    val result = tuple match {
    
    
        case (0, _) => "0 ..." //是第一个元素是0的元组
        case (y, 0) => "" + y + "0" // 匹配后一个元素是0的对偶元组
        case (a, b) => "" + a + " " + b
        case _ => "something else" //默认

    }
    println(result)
}

タプルでの特別な試合

出力タプルの最初の要素
val list: List[(String, Int)] = List(("a", 1), ("b", 2), ("c", 3))
// 输出元组中的第一个元素
for (elem <- list) {
    
    
  println(elem._1)
}
for ((word, count) <- list) {
    
    
  println(word)
}
// 如果只需要元组中的某个位置的值,那么其他位置可以写为_
for ((word, _) <- list) {
    
    
  println(word)
}
要素の値
for (("a",count) <- list){
    
    
  println(count)
}
要素が一致したら、タプル要素に名前を付けます
val (name, age, addr): (String, Int, String) = ("zhangsan", 18, "北京")
println(name)
キーは変更せず、値* 2
val list: List[(String, Int)] = List(("a", 1), ("b", 2), ("c", 3))
for((word, count) <- list) {
    
    
  println((word, count * 2))
}
println(list.map(kv => {
    
    (kv._1,kv._2*2)}))

// 如果函数列表中,只有一个参数,那么小括号可以用大括号代替
val tuples: List[(String, Int)] = list.map {
    
     t =>
  t match {
    
    
    case (word, count) => (word, count * 2)
  }
}
println(tuples)

// 如果匿名函数使用模式匹配,必须使用大括号括起来
val tuples: List[(String, Int)] = list.map {
    
    
  case (word, count) => (word, count * 2)
}
println(tuples)

val list = List(("a",("a",5)),("b",("b",10)),("c",("c",20)))
// 使用模式匹配对值*2
val tuples: List[(String, (String, Int))] = list.map {
    
    
  case (word, (word2, count)) => (word, (word2, count*2))
}
println(tuples)

一致オブジェクト

  • パターンがオブジェクトと一致すると、コンパニオンオブジェクトのunapplyメソッドが呼び出され、属性の値が取得されます。
object Scala04_Match {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val stu = Student04("zhangsan", 21)
    val res = stu match {
    
    
      //模式匹配对象时,会调用伴生对象中的unapply方法获取属性的值
      case Student04("zhangsan", 22) => true
      case _ => false
    }
    println(res)
  }
}

class Student04(var name: String, var age: Int){
    
    }

object Student04{
    
    
  // 根据属性创建对象
  def apply(name: String, age: Int): Student04 = new Student04(name,age)

  // 根据对象获取属性
  def unapply(stu: Student04): Option[(String, Int)] = {
    
    
    if (stu == null) {
    
    
      None
    }else {
    
    
      Some(stu.name, stu.age)
    }
  }
}

サンプルクラス

  • クラスを宣言するときのユースケースの変更。
  • サンプルクラスの最下層は、オブジェクトのプロパティを取得するためにunapplyメソッドを自動的に実装します。
object Scala05_Match {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val stu = new Student05("lisi", 18)
    val res = stu match {
    
    
      case Student05("lisi", 18) => true
      case _ => false
    }
    println(res)
  }
}

// 样例类底层会自动实现unapply方法,获取对象的属性
case class Student05(var name: String, var age: Int){
    
    }

おすすめ

転載: blog.csdn.net/FlatTiger/article/details/114647287