使用某些 Scala Option 方法的示例

发布于 2024-11-26 13:46:50 字数 351 浏览 1 评论 0原文

我已阅读博客文章推荐我此处。现在我想知道这些方法有什么用处。您能否展示使用 forall(而不是 foreach)和 OptiontoList 的示例?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一萌ing 2024-12-03 13:46:50
  • map:允许您转换 Option“内部”的值,正如您可能已经了解 List 一样。这个操作使Option成为一个函子(如果你想吓唬你的同事,你可以说“endofunctor”)
  • flatMapOption实际上是一个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:对内部的值(如果存在)执行某些操作。
  • isDefinedisEmpty:确定此Option是否包含值。
  • forallexists:测试给定谓词是否适用于该值。 foralloption.map(test(_)).getOrElse(true) 相同,exists 相同,只是与 false 作为默认值。
  • toList:令人惊讶的是,它将 Option 转换为 List
  • map: Allows you to transform a value "inside" an Option, as you probably already know for Lists. This operation makes Option a functor (you can say "endofunctor" if you want to scare your colleagues)
  • flatMap: Option is actually a monad, and flatMap 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 an Option, but the value you have is already "wrapped" in an Option, so flatMap saves you the unwrapping before applying the function. E.g. if you have an Option[Map[K,V]], you can write mapOption.flatMap(_.get(key)). If you would use a simple map here, you would get an Option[Option[V]], but with flatMap you get an Option[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 type Option[Option[T]], flatten turns it into an Option[T]. It is the same as flatMap(identity(_)).
  • orElse: If you have several alternatives wrapped in Options, and you want the first one that holds actually a value, you can chain these alternatives with orElse: steakOption.orElse(hamburgerOption).orElse(saladOption)
  • getOrElse: Get the value out of the Option, 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 this Option holds a value.
  • forall, exists: Tests if a given predicate holds for the value. forall is the same as option.map(test(_)).getOrElse(true), exists is the same, just with false as default.
  • toList: Surprise, it converts the Option to a List.
北凤男飞 2024-12-03 13:46:50

Option 上的许多方法可能更多的是为了统一(带有集合)而不是为了它们的有用性,因为它们都是非常小的函数,所以不遗余力,但它们有一个目的,它们的含义是一旦你熟悉了集合框架就一目了然了(正如人们常说的,Option就像一个列表,不能有多个元素)。

forall 检查选项内值的属性。如果没有值,则检查通过。例如,如果在汽车租赁中,您可以使用一名 additionalDriver: Option[Person],那么您可以

additionalDriver.forall(_.hasDrivingLicense)

执行与允许多个额外驾驶员并且您有一个列表时完全相同的操作。

toList 可能是一个有用的转换。假设您有选项:List[Option[T]],并且您想要获取一个 List[T],其中所有选项的值均为 Some。你可以这样做

for(option <- options; value in option.toList) yield value

(或者更好的 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 do

additionalDriver.forall(_.hasDrivingLicense)

exactly 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

for(option <- options; value in option.toList) yield value

(or better options.flatMap(_.toList))

吃兔兔 2024-12-03 13:46:50

我有一个 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 either Nil or List with only one element. I can retrieve it as Option with discoverBinding. I find it convenient to be able to convert Option to List (that either empty or has one element) with toList method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文