Scala Map#get 和 Some() 的返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9389902/
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#get and the return of Some()
提问by meriley
Im using scala Map#getfunction, and for every accurate query it returns as Some[String]
我使用 scalaMap#get函数,对于每个准确的查询,它返回为Some[String]
IS there an easy way to remove the Some?
有没有简单的方法去除Some?
Example:
例子:
def searchDefs{
print("What Word would you like defined? ")
val selection = readLine
println(selection + ":\n\t" + definitionMap.get(selection))
}
When I use this method and use the following Input:
当我使用此方法并使用以下输入时:
What Word would you like defined? Ontology
The returned Value is:
返回值为:
Ontology:
Some(A set of representational primitives with which to model a domain of knowledge or discourse.)
I would like to remove the Some() around that.
我想删除周围的 Some() 。
Any tips?
有小费吗?
回答by Frank
There are a lot of ways to deal with the Optiontype. First of all, however, do realize how much better it is to have this instead of a potential nullreference! Don't try to get rid of it simply because you are used to how Java works.
有很多方法可以处理Option类型。但是,首先要意识到拥有这个而不是潜在的null参考要好得多!不要仅仅因为您已经习惯了 Java 的工作方式就试图摆脱它。
As someone else recently stated: stick with it for a few weeks and you will moan each time you have to get back to a language which doesn't offer Optiontypes.
正如其他人最近所说:坚持使用它几个星期,每次你不得不回到一种不提供Option类型的语言时,你都会抱怨。
Now as for your question, the simplest and riskiest way is this:
现在至于你的问题,最简单和最危险的方法是这样的:
mymap.get(something).get
Calling .geton a Someobject retrieves the object inside. It does, however, give you a runtime exception if you had a Noneinstead (for example, if the key was not in your map).
调用.get一个Some对象会检索里面的对象。但是,如果您有一个None替代(例如,如果键不在您的地图中),它确实会给您一个运行时异常。
A much cleaner way is to use Option.foreachor Option.maplike this:
更简洁的方法是使用Option.foreach或Option.map像这样:
scala> val map = Map(1 -> 2)
map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2)
scala> map.get(1).foreach( i => println("Got: " + i))
Got: 2
scala> map.get(2).foreach( i => println("Got: " + i))
scala>
As you can see, this allows you to execute a statement if and only if you have an actual value. If the Optionis Noneinstead, nothing will happen.
如您所见,当且仅当您具有实际值时,这允许您执行语句。如果Option是None,则什么都不会发生。
Finally, it is also popular to use pattern matching on Optiontypes like this:
最后,在这样的Option类型上使用模式匹配也很流行:
scala> map.get(1) match {
| case Some(i) => println("Got something")
| case None => println("Got nothing")
| }
Got something
回答by Albaro Pereyra
I personally like using .getOrElse(String)and use something like "None" as a default i.e. .getOrElse("None").
我个人喜欢使用.getOrElse(String)“无”之类的东西作为默认值,即.getOrElse("None").

