5. Scala the match, pattern matching, samples class

1. match

Scala in the match expression allows you to use any mode is selected, the default sample with an underscore (_) to represent. The sample can be any constants, strings, etc., do not need every last option plus break (Scala is implicit in the break, the situation is completely under an option to continue the implementation of an option will not appear). match expressions can return values.

2. Pattern Matching

Pattern matching applications: switch statement, the type of query, and the destructor (acquiring different portions of the complex expression).

2.1 Guard

Guard can be any Boolean condition.

val ch = ""
val sign = ch match {
  case "+" => 1
  case "-" => -1
  case _ if ch.isEmpty() => 0
  case _ => -999
}
println(sign)  // 0
2.2 constant pattern-matching type, the array / list / tuple
// 匹配常量:如果常量是小写字母开头,加反引号
val a = 123
val b = 123
val res01 = a match {
  case Pi => "a is Pi"
  case `b` => b
  case _ => "unknown"
}
println(res01)  // 123
// 匹配类型
val obj: Any = "1232dfsd"
val res02 = obj match {
  case x: Int => "Int: " + x
  case x: String if (obj.toString.toCharArray.filter(x => Character.isDigit(x)).size == obj.toString.size) => "String: " + Integer.parseInt(x)
  case x: BigInt => "BigInt: " + Integer.MAX_VALUE
  case _ => 0
}
println(res02) // 0
// 匹配数组、列表和元组
def f(arr: Array[Any]): String = arr match {
  case Array(0) => "0"
  case Array(x, y) => x + " " + y
  case Array(0, _*) => "0 ..."
  case _ => "something else"
}
println(f(Array(0, "aa")))  // 0 aa
println(f(Array(0)))        // 0
println(f(Array("aa")))     // something else
println(f(Array(0, 3, 5)))  // 0 ...
Extractor 2.3
3. Sample Class

Scala provides examples of class pattern matching is optimized.

Released eight original articles · won praise 0 · Views 113

Guess you like

Origin blog.csdn.net/qq_42994084/article/details/105327159