人人都说模式匹配是函数式语言的一大特色。为什么?
我不能简单地使用 ifs 和 switch case 来处理所有事情吗?
我想了解使用模式匹配代替常规过程编程 ifs 和 switch case 的优势
最佳答案
我首先要注意的是,您没有使用模式匹配“代替”switch 语句。 Scala 没有 switch
语句,它有的是 match block ,里面的 case 从表面上看与 switch 语句非常相似。
具有模式匹配的匹配 block 可以完成 switch
所做的一切,甚至更多。
A) 它不仅限于原始类型和 Oracle 在语言规范中选择“祝福”的其他类型(字符串和枚举)。如果您想匹配自己的类型,请继续!
B)模式匹配也可以提取。例如,对于一个元组:
val tup = ("hello world", 42)
tup match {
case (s,i) =>
println("the string was " + s)
println("the number was " + i
}
有一个列表:
val xs = List(1,2,3,4,5,6)
xs match {
case h :: t =>
// h is the head: 1
// t is the tail: 2,3,4,5,6
// The :: above is also an example of matching with an INFIX TYPE
}
用案例类
case class Person(name: String, age: Int)
val p = Person("John Doe", 42)
p match {
case Person(name, 42) =>
//only extracting the name here, the match would fail if the age wasn't 42
println(name)
}
C) 模式匹配可用于赋值和 for-comprehensions,而不仅仅是在匹配 block 中:
val tup = (19,73)
val (a,b) = tup
for((a,b) <- Some(tup)) yield a+b // Some(92)
D) 匹配 block 是表达式,而不是语句
这意味着它们会根据匹配的案例的主体进行评估,而不是完全通过副作用来行动。这对于函数式编程至关重要!
val result = tup match { case (a,b) => a + b }
关于java - 使用 scala 模式匹配而不是 java switch case 有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355060/