Scala Map#获取和返回Some() [英] Scala Map#get and the return of Some()
问题描述
我使用scala Map#get
函数,并且对于每个准确的查询,它返回为 Some [String]
/ p>
有没有一个简单的方法来删除一些
?
示例:
def searchDefs {
print(你想要定义什么Word)
val selection = readLine
println(selection +:\\\
\t+ definitionMap.get(selection))
}
当我使用此方法并使用以下输入:
什么你想定义一个词吗?本体
返回的值为:
本体:
一些(一组用于建模知识或话语域的表示基元)
我想删除Some()。
任何提示?
有很多方法来处理 Option
类型。首先,但是,请确实意识到这更好,而不是潜在的 null
引用!不要试图摆脱它只是因为你习惯了Java的工作原理。
正如其他人最近所说:坚持几个星期,你会每次你必须回到不提供选项
类型的语言的呻吟。
现在你的问题,最简单和最危险的方法是这样的:
mymap.get(something).get
在上调用
对象检索内部的对象。但是,如果您有 .get
一些无
(例如,如果密钥不在您的地图中),那么它会给您一个运行时异常。
更简单的方法是使用 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))
得到:2
scala> map.get(2).foreach(i => println(Got:+ i))
scala>
如您所见,这个允许您在且仅当具有实际值时执行语句。如果选项
是无
,则不会发生任何事情。
<最后,在
选项
类型下使用模式匹配也很受欢迎: 阶> map.get(1)match {
| case(i)=> println(Got something)
| case None => println(Got nothing)
|
有东西
Im using scala Map#get
function, and for every accurate query it returns as Some[String]
IS there an easy way to remove the 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.
Any tips?
There are a lot of ways to deal with the Option
type. First of all, however, do realize how much better it is to have this instead of a potential null
reference! Don't try to get rid of it simply because you are used to how Java works.
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 Option
types.
Now as for your question, the simplest and riskiest way is this:
mymap.get(something).get
Calling .get
on a Some
object retrieves the object inside. It does, however, give you a runtime exception if you had a None
instead (for example, if the key was not in your map).
A much cleaner way is to use Option.foreach
or Option.map
like this:
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 Option
is None
instead, nothing will happen.
Finally, it is also popular to use pattern matching on Option
types like this:
scala> map.get(1) match {
| case Some(i) => println("Got something")
| case None => println("Got nothing")
| }
Got something
这篇关于Scala Map#获取和返回Some()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!