Scala 选项:映射与模式匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21923600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:04:57  来源:igfitidea点击:

Scala Option: map vs Pattern Matching

scala

提问by Prasanna

While dealing with Optionin Scala what are the things I should be considering to decide whether to map or patten match? For example, if I have Option[MyClass], I can deal with it the following ways:

Option在 Scala 中处理时,我应该考虑哪些事情来决定是映射还是模式匹配?例如,如果我有Option[MyClass],我可以通过以下方式处理它:

def getList(myOptionInstance: Option[MyClass]): List[String] =
  myOptionInstance map (...) getOrElse(List.empty[String])

or

或者

def getList(myOptionInstance: Option[MyClass]): List[String] = myOptionInstance match {
  case Some(mySomeInstance) => .....
  case None => List.empty[String]
}

When will I choose one over the other?

我什么时候会选择一个?

回答by vptheron

I second @rarry: foldis the preferred way to deal with this.

我第二次@rarry:fold是处理这个问题的首选方式。

Some prefer pattern matching because it's "cool" (whatever it means) and sometimes easier to read.

有些人更喜欢模式匹配,因为它“很酷”(不管它意味着什么),有时更容易阅读。

I try to avoid using getOrElsebecause it does not force you to use the same type for the default value as the type wrapped in your Option:

我尽量避免使用,getOrElse因为它不会强制您对默认值使用与您的Option.

def getOrElse[B >: A](default: ? B): B

So you can write:

所以你可以写:

val v = Some(42).getOrElse("FortyTwo")

Here vhas type Any. It's very easy to see the problem with such a stupid example but sometimes it's not as obvious and can lead to issues.

这里v有类型Any。用这样一个愚蠢的例子很容易看出问题,但有时它并不那么明显,可能会导致问题。

While fold:

虽然fold

def fold[B](ifEmpty: ? B)(f: (A) ? B): B

It forces you to return the same type for both branches.

它强制您为两个分支返回相同的类型。

scala> Some(42).fold("fortyTwo")(v => v)
<console>:8: error: type mismatch;
 found   : Int
 required: String
              Some(42).fold("fortyTwo")(v => v)

回答by mauhiz

Pattern matching is :

模式匹配是:

  • 稍微有效率
  • 不是关于子类型的肛门(在这种情况下@rarry 必须添加类型提示)
  • 更容易阅读
  • Martin Oderksy 认可:https://stackoverflow.com/a/5332657/578101

回答by rarry

I would go for this:

我会这样做:

myOptionInstance.fold(Nil: List[String])(...)