选项上的 Scala 映射方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38866711/
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
Scala map method on option
提问by vivman
I am new to scala, please help me with the below question.
我是 Scala 的新手,请帮助我解决以下问题。
Can we call map method on an Option? (e.g. Option[Int].map()?).
我们可以在 Option 上调用 map 方法吗?(例如 Option[Int].map()?)。
If yes then could you help me with an example?
如果是,那么你能帮我举个例子吗?
回答by Iadams
Yes:
是的:
val someInt = Some (2)
val noneInt:Option[Int] = None
val someIntRes = someInt.map (_ * 2) //Some (4)
val noneIntRes = noneInt.map (_ * 2) //None
See docs
查看文档
You can view an option as a collection that contains exactly 0 or 1 items. Mapp over the collection gives you a container with the same number of items, with the result of applying the mapping function to every item in the original.
您可以将一个选项视为包含正好 0 或 1 个项目的集合。集合上的映射为您提供了一个具有相同项目数的容器,结果是将映射函数应用于原始项目中的每个项目。
回答by Luka Jacobowitz
Here's a simple example:
这是一个简单的例子:
val x = Option(5)
val y = x.map(_ + 10)
println(y)
This will result in Some(15).
If xwere Noneinstead, ywould also be None.
这将导致Some(15). 如果x是None,y也将是None。
回答by Vladimir Salin
Sometimes it's more convenient to use foldinstead of mapping Options. Consider the example:
有时使用fold而不是 mapping更方便Option。考虑这个例子:
scala> def printSome(some: Option[String]) = some.fold(println("Nothing provided"))(println)
printSome: (some: Option[String])Unit
scala> printSome(Some("Hi there!"))
Hi there!
scala> printSome(None)
Nothing provided
You can easily proceed with the real value inside fold, e.g. map it or do whatever you want, and you're safe with the default fold option which is triggered on Option#isEmpty.
您可以轻松地处理内部的真实值fold,例如映射它或做任何您想做的事情,并且您可以安全地使用在 上触发的默认折叠选项Option#isEmpty。

