使用 scala 模式匹配而不是 java switch case 的优点是什么? [英] What is the advantage of using scala pattern matching instead of java switch case?

查看:22
本文介绍了使用 scala 模式匹配而不是 java switch case 的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都说模式匹配是函数式语言的一个很好的特性.为什么?

Everybody says that pattern matching is a great feature in functional languages. Why?

我不能简单地使用 ifs 和 switch case 来处理所有事情吗?

Can't I simple use ifs and switch cases for everything?

我想了解使用模式匹配代替常规过程编程 ifs 和 switch case 的优势

I'd like to understand the advantages of using pattern matching instead of regular procedural programming ifs and switch cases

推荐答案

我首先要指出的是,您不使用模式匹配代替"switch 语句.Scala 没有 switch 语句,它有的是匹配块,里面的 case 表面上看起来非常类似于 switch 语句.

I'd first like to note that you don't use pattern matching "instead" of switch statements. Scala doesn't have switch statements, what it does have is match blocks, with cases inside that superficially look very similar to a switch statement.

具有模式匹配的匹配块可以完成 switch 所做的一切,以及更多.

Match blocks with pattern matching does everything that switch does, and much more.

A) 它不仅限于原语和 Oracle 在语言规范中选择祝福"的其他类型(字符串和枚举).如果您想匹配自己的类型,请继续!

A) It's not restricted to just primitives and other types that Oracle have chosen to "bless" in the language spec (Strings and Enums). If you want to match on your own types, go right ahead!

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,而不仅仅是在匹配块中:

C) pattern matching can be used in value assignment and for-comprehensions, not just in match blocks:

val tup = (19,73)

val (a,b) = tup

for((a,b) <- Some(tup)) yield a+b // Some(92)

D) 匹配块是表达式,而不是语句

这意味着它们对匹配的任何情况的主体进行评估,而不是完全通过副作用起作用.这对于函数式编程至关重要!

This means that they evaluate to the body of whichever case was matched, instead of acting entirely through side-effects. This is crucial for functional programming!

val result = tup match { case (a,b) => a + b }

这篇关于使用 scala 模式匹配而不是 java switch case 的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆