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
Optiontype. First of all, however, do realize how much better it is to have this instead of a potentialnullreference! 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
Optiontypes.Now as for your question, the simplest and riskiest way is this:
Calling
.geton aSomeobject retrieves the object inside. It does, however, give you a runtime exception if you had aNoneinstead (for example, if the key was not in your map).A much cleaner way is to use
Option.foreachorOption.maplike this:As you can see, this allows you to execute a statement if and only if you have an actual value. If the
OptionisNoneinstead, nothing will happen.Finally, it is also popular to use pattern matching on
Optiontypes like this: