Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Lesson 27: practical Analysis of Type, Array, List, Tuple pattern matching

Shulou Source: shulou.com Published: 2022-06-03 05:57:31 09月20日 Update

In addition to ordinary × ×, string type pattern matching, scala also provides many forms of pattern matching. For example, Type, Array, List, Tuple

Let's explain it through the code.

Type pattern matching: judging the type of incoming value

Def match_type (t: Any) = t match {case p: Int = > println ("It is an Integer!") Case p: String = > println ("It is a String! the content is:" + p) case m: Map [_, _] = > m.foreach (println) case _ = > println ("Unknown Type")} match_type (1) match_type ("Spark") match_type (Map ("Spark"-> "scala language"))

The running result is as follows

It is an Integer!It is a String! The content is: Spark (Spark,scala language)

Two _ in the special description Map [_, _], indicating any type. Equivalent to type Map = Predef.Map [A, B] but cannot be written as Map [Any,Any]

Array pattern matching:

Def match_array (arr: Any) = arr match {case Array (x) = > println ("Array (1):", x) / / an array of length 1, where x represents the value in the array case Array (x) = > println ("Array (2):", x) / / an array of length 2 X represents the first value in the array, case Array (x < *) = > println ("any one-dimensional array:", x) / / any length array Take the first value case Array (_ *) = > println ("any one-dimensional array") / / arbitrary length array} match_array (Array (0)) match_array (Array ("spark")) match_array (Array ("spark", "scala")) match_array (Array ("spark", "scala", 0Pol 4))

List matching:

Def match_list (lst: Any) = lst match {case 0:: Nil = > println ("List:" + 0) / / Nil means empty list case List (x) = > println ("List:" + x) case x: Nil = > println ("List:"+ x) case x:: tail = > println (" List: "+" element list ") / / tail represents all the remaining elements of List} Match_list (List (0)) match_list (List ("spark")) match_list (List ("spark") "hadoop")) match_list (List ("spark", 1, 2, 4, 5))

Tuple matching

Def match_tuple (t: Any) = t match {case (0something else _) = > println ("tuple, the first value is 0") case (xpriy) = > println ("tuple, the value is:" + x + "," + y) case _ = > println ("something else")} match_tuple ((0cmlgx')) match_tuple (('YLINGOLING x')) match_tuple ((0Med 1m 2GI 3))

Tags: Array pattern type length representative element one-dimensional ordinary special two code character string form result run actual combat Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Information Redmi Huawei NVidia