使用某些 Scala Option 方法的示例
I have read the blog post recommended me here. Now I wonder what some those methods are useful for. Can you show examples of using forall
(as opposed to foreach
) and toList
of Option
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
map
:允许您转换Option
“内部”的值,正如您可能已经了解List
一样。这个操作使Option
成为一个函子(如果你想吓唬你的同事,你可以说“endofunctor”)flatMap
:Option
实际上是一个monad,flatMap
使其成为一个(与单个值的构造函数之类的东西一起)。如果您有一个将值转换为Option
的函数,但您拥有的值已经“包装”在Option
中,则可以使用此方法,因此flatMap 会在应用函数之前保存您的展开操作。例如,如果您有一个
Option[Map[K,V]]
,则可以编写mapOption.flatMap(_.get(key))
。如果您在这里使用简单的map
,您将得到一个Option[Option[V]]
,但是使用flatMap
您将得到一个>选项[V]
。这种方法比您想象的要酷,因为它允许以非常灵活的方式将函数链接在一起(这就是 Haskell 喜欢 monad 的原因之一)。展平
:如果您有一个Option[Option[T]]
类型的值,展平
会将其转换为Option[T]
。它与flatMap(identity(_))
相同。orElse
:如果您有多个选项包含在Option
中,并且您希望第一个选项实际上包含一个值,则可以使用orElse
将这些选项链接起来code>:steakOption.orElse(hamburgerOption).orElse(saladOption)
getOrElse
:从Option
中获取值,但指定默认值如果它为空,例如nameOption.getOrElse("unknown")
。foreach
:对内部的值(如果存在)执行某些操作。isDefined
、isEmpty
:确定此Option
是否包含值。forall
、exists
:测试给定谓词是否适用于该值。forall
与option.map(test(_)).getOrElse(true)
相同,exists
相同,只是与false
作为默认值。toList
:令人惊讶的是,它将Option
转换为List
。map
: Allows you to transform a value "inside" anOption
, as you probably already know forList
s. This operation makesOption
a functor (you can say "endofunctor" if you want to scare your colleagues)flatMap
:Option
is actually a monad, andflatMap
makes it one (together with something like a constuctor for a single value). This method can be used if you have a function which turns a value into anOption
, but the value you have is already "wrapped" in anOption
, soflatMap
saves you the unwrapping before applying the function. E.g. if you have anOption[Map[K,V]]
, you can writemapOption.flatMap(_.get(key))
. If you would use a simplemap
here, you would get anOption[Option[V]]
, but withflatMap
you get anOption[V]
. This method is cooler than you might think, as it allows to chain functions together in a very flexible way (which is one reason why Haskell loves monads).flatten
: If you have a value of typeOption[Option[T]]
,flatten
turns it into anOption[T]
. It is the same asflatMap(identity(_))
.orElse
: If you have several alternatives wrapped inOption
s, and you want the first one that holds actually a value, you can chain these alternatives withorElse
:steakOption.orElse(hamburgerOption).orElse(saladOption)
getOrElse
: Get the value out of theOption
, but specify a default value if it is empty, e.g.nameOption.getOrElse("unknown")
.foreach
: Do something with the value inside, if it exists.isDefined
,isEmpty
: Determine if thisOption
holds a value.forall
,exists
: Tests if a given predicate holds for the value.forall
is the same asoption.map(test(_)).getOrElse(true)
,exists
is the same, just withfalse
as default.toList
: Surprise, it converts theOption
to aList
.Option 上的许多方法可能更多的是为了统一(带有集合)而不是为了它们的有用性,因为它们都是非常小的函数,所以不遗余力,但它们有一个目的,它们的含义是一旦你熟悉了集合框架就一目了然了(正如人们常说的,Option就像一个列表,不能有多个元素)。
forall 检查选项内值的属性。如果没有值,则检查通过。例如,如果在汽车租赁中,您可以使用一名
additionalDriver: Option[Person]
,那么您可以执行与允许多个额外驾驶员并且您有一个列表时完全相同的操作。
toList 可能是一个有用的转换。假设您有选项:List[Option[T]],并且您想要获取一个 List[T],其中所有选项的值均为 Some。你可以这样做
(或者更好的
options.flatMap(_.toList)
)Many of the methods on Option may be there more for the sake of uniformity (with collections) rather than for their usefulness, as they are all very small functions and so do not spare much effort, yet they serve a purpose, and their meanings are clear once you are familiar with the collection framework (as is often said, Option is like a list which cannot have more than one element).
forall checks a property of the value inside an option. If there is no value, the check pass. For example, if in a car rental, you are allowed one
additionalDriver: Option[Person]
, you can doexactly the same thing that you would do if several additional drivers were allowed and you had a list.
toList may be a useful conversion. Suppose you have options: List[Option[T]], and you want to get a List[T], with the values of all of the options that are Some. you can do
(or better
options.flatMap(_.toList)
)我有一个
toList
方法的实际例子。您可以在 scaldi (我的 Scala 依赖注入框架)中找到它href="https://github.com/OlegIlyenko/scaldi/blob/f3697ecaa5d6e96c5486db024efca2d3cdb04a65/src/main/scala/scaldi/Module.scala" rel="nofollow">Module.scala 在第 72 行:https://github.com/OlegIlyenko/scaldi/blob/f3697ecaa5d6e96c5486db024efca2d3cdb04a65/src/main/scala/scaldi/Module.scala#L72
在此上下文中
getBindings
方法可以返回Nil
或仅包含一个元素的List
。我可以使用discoverBinding
将其作为Option
检索。我发现使用toList
方法将Option
转换为List
(空或有一个元素)很方便。I have one practical example of
toList
method. You can find it in scaldi (my Scala dependency injection framework) in Module.scala at line 72:https://github.com/OlegIlyenko/scaldi/blob/f3697ecaa5d6e96c5486db024efca2d3cdb04a65/src/main/scala/scaldi/Module.scala#L72
In this context
getBindings
method can return eitherNil
orList
with only one element. I can retrieve it asOption
withdiscoverBinding
. I find it convenient to be able to convertOption
toList
(that either empty or has one element) withtoList
method.