Scala Map#get and the return of Some()

前端 未结 2 337
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 18:18

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

相关标签:
2条回答
  • 2020-12-05 18:52

    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
    
    0 讨论(0)
  • 2020-12-05 19:04

    I personally like using .getOrElse(String) and use something like "None" as a default i.e. .getOrElse("None").

    0 讨论(0)
提交回复
热议问题