当前位置:网站首页>Scala pattern matching
Scala pattern matching
2022-07-27 01:01:00 【Drive the tractor home】
Catalog
One 、 Introduction to pattern matching
1.1 Overview of pattern matching
Two 、 Pattern matching instance
One 、 Introduction to pattern matching
1.1 Overview of pattern matching
Scala Provides a powerful pattern matching mechanism , It is also widely used .
A pattern match contains a series of alternatives , Each starts with keywords case. Each alternative contains a pattern and one or more expressions . The arrow symbol => It separates the pattern from the expression .
1.2 Type of pattern matching
Include :
- Constant mode
- Variable mode
- Constructor mode
- Sequence pattern
- Tuple mode
Two 、 Pattern matching instance
object Test01 {
/**
* Character constant matching
*
* @param score
* @param name
*/
def studentScore02(score: String, name: String) = {
score match {
case "A" => println(" good ")
case "B" => println(" good ")
case "C" => if (name == "kangll") println("kangll good boy.")
case _ => {
if (name == "kangll" && score != "A") {
println(name + " Work hard , Your grades can be good !")
}
}
}
}
/**
* Match database connection information according to keywords ( Constant matching )
*
* @param sparkSession spark Connect
* @param dbSourceType
* @param tableName
*/
def getMySQLDataConnByTableName(sparkSession: SparkSession, dbSourceType: String, tableName: String) = {
dbSourceType.toLowerCase match {
case "calc" => MysqlJdbcUil.getDataBySql(sparkSession, calcMySQLURL, calcMySQLUSER, calcMYSQLPWD, tableName)
case "ddqs" => MysqlJdbcUil.getDataBySql(sparkSession, calcMySQLURL, calcMySQLUSER, calcMYSQLPWD, tableName)
case "ress" => MysqlJdbcUil.getDataBySql(sparkSession, calcMySQLURL, calcMySQLUSER, calcMYSQLPWD, tableName)
case _ => null
}
}
/**
* Scala There is a special type of , be called Option.Option There are two kinds of value , One is Some, It's worth it , One is None, No value .
* Option Usually used in pattern matching , Used to determine whether a variable has a value or no value , This is more than null Come more concise and clear
*
* @param name
*/
def getGrade(name: String): Unit = {
val grades: Map[String, String] = Map("kangll" -> "a", "zhangsanfeng" -> "b", "zhangwuji" -> "c")
// grade The type of Option
val grade: Option[String] = grades.get(name)
grade match {
case Some(grade) => println("your grade is " + grade)
case None => println("Sorry, your grade is not in this system")
}
}
/**
* Variable matching
*/
def variablePatten(x: Any) = {
x match {
case x if (x == 5) => x
case x if (x == "scala") => x
case _ =>
}
}
/** Sample class */
case class Person(userName: String, age: Int)
/**
* The constructor pattern refers to , Directly in case Statement followed by a class constructor , The matching content is placed in the constructor parameters .
*
* @param p
* @return
*/
def constructorPattern(p: Person) = {
p match {
case Person(userName, age) => "userName = " + userName + ", age = " + age
case _ => "Other"
}
}
/**
* Sequence patterns are used for matching such as arrays Array、 list List、Range Such a set of linear structures , In fact, the principle is also through case class It works .
*
* @param p
*/
def sequencePattern(p: Any) = {
p match {
// Sequence pattern matching ,_* Indicates that the remaining content is matched ,first、second The match array p The first of all 、 Two elements
case Array(first, second, _*) => first + ", " + second
// _ Configuration set p The first element of , But not assigned to any variable
case List(_, second, _*) => second
case _ => "Other"
}
}
/**
* Variable binding mode
*
* @param t
*/
def variableBindingPattern(t: Any) = {
t match {
// Variable binding , Use variable names ( Here is e)
// And @ Symbol , If the following pattern matches successfully , Then take the overall matching result as the return value
case List(_, [email protected](_, _, _)) => e
case _ => Nil
}
}
def main(args: Array[String]): Unit = {
this.studentScore02("C", "kangll")
getGrade("kangll")
getGrade("long")
constructorPattern(new Person("kangll", 20))
println(this.sequencePattern(List("spark", "Hive", "SparkSQL")))
println(this.sequencePattern(Array("SparkR", "Spark Streaming", "Spark MLib")))
println(this.variableBindingPattern(List(List(1, 2, 3), List(2, 3, 4))))
}
}
边栏推荐
猜你喜欢
随机推荐
JS screen detection method summary 2021-10-05
Reasons why row locks in MySQL upgrade table locks
10 - CentOS 7 上部署MySql
基于Flink实时计算Demo:用户行为分析(四:在一段时间内到底有多少不同的用户访问了网站(UV))
[CISCN2019 华北赛区 Day1 Web5]CyberPunk
[SQL注入] 扩展注入手法
[By Pass] WAF 的绕过方式
Leetcode 301 week
flink需求之—ProcessFunction(需求:如果30秒内温度连续上升就报警)
[NPUCTF2020]ezinclude
Doris或StarRocks Jmeter压测
JSCORE day_ 04(7.5)
Hidden index and descending index in MySQL 8.0 (new feature)
SSRF explanation and burp automatic detection SSRF
使用tika 判断文件类型
Spark On YARN的作业提交流程
2022.7.10DAY602
Golang implements AES with five encryption mode functions, encrypt encryption and decryption string output
redis——缓存雪崩、缓存穿透、缓存击穿
Flink的容错机制(checkpoint)

![[RootersCTF2019]I_<3_Flask](/img/69/1c77e45e939cf86bb75be8a6c42574.png)

![[watevrCTF-2019]Cookie Store](/img/24/8baaa1ac9daa62c641472d5efac895.png)

![[CTF 真题] 2018-网鼎杯-Web-Unfinish](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)



