Scala 选项:地图与模式匹配 [英] Scala Option: map vs Pattern Matching

查看:41
本文介绍了Scala 选项:地图与模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While dealing with Option in 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:

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

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?

推荐答案

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

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

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

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

我尽量避免使用 getOrElse,因为它不会强制您使用与 Option 中包装的类型相同的类型作为默认值:

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

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

所以你可以写:

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

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

Here v has 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.

虽然折叠:

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)

这篇关于Scala 选项:地图与模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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