Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with Some() and Option() in Scala

Tags:

scala

I've been fighting with the concept of the functional way of parsing a JSON string in Scala and ran flat into the wall with Option(something) being returned. I popped the questionand the helpful answers came streaming in.

The problem is, as someone being pretty new to Scala, what is the correct way?

Currently I'm doing this:

import util.parsing.json.JSON._

object JsonSoap {
  def main(args: Array[String]) {
    val x = parseFull("""{"name":"Joe","surname":"SOAP"}""")

    val y = x collect {
      case m: Map[_, _] => m collect {
        case (key: String, value: String) => key -> value
      }
    }

    val z = for (m <- y; name <- m.get("name"); surname <- m.get("surname"))
    yield {
      <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <Person>
            <Name>{name}</Name>
            <Surname>{surname}</Surname>
          </Person>
        </soap:Body>
      </soap:Envelope>
    }

    println(z)
  }
}

I'm still stuck with Some()

Is there a nice pattern to solving my problem? Surely this has to be well explored territory. How can I improve my code?

like image 522
Jack Avatar asked Feb 20 '12 16:02

Jack


People also ask

How do you use some and options in Scala?

An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.

What does some () do in Scala?

Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some. We can use this with the collection.

Why do we use option in Scala?

Scala's Option is particularly useful because it enables management of optional values in two self-reinforcing ways: Type safety – We can parameterize our optional values. Functionally aware – The Option type also provides us with a set of powerful functional capabilities that aid in creating fewer bugs.

Why might you choose to use option rather than using null in Scala?

In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.


1 Answers

You are not "stuck" with Some - you have the advantage that you have a Some! In Java, you would be stuck with a value whose type did not express the fact that it might not actually exist!

MyThing recklessly = apiCall.getMeAThing();
recklessly.iSureHopeImNotNull();  //OH NOES!

Compare that to this

apiCall.getMeAThing foreach (_.cannotPossiblyBeNull)

The Option datatype means that the "might not exist" bit of your query is actually baked into the return type of the query. Please stick with Option - in a few weeks you will be pulling out your hair when you go to write Java code and it's not there!

Shooting down your objections

You might say:

Aw, but I need to take the value I have and add 1 to it

I say:

apiCall.getMeAThing map (_ + 1)

You might say

Aw, but I need to pass it to a method, defaulting to the empty String if I have null

I say:

foo( apiCall.getMeAThing getOrElse "" )

You might say

Aw, but I use that value to call another API method and get something else

I say:

apiCall.getMeAThing flatMap apiCall.getMeAnotherThing

You'll definitely say

Aw but that's awfully inefficient with all those object creations

I say: "try it, it will be just fine"

like image 183
oxbow_lakes Avatar answered Nov 07 '22 19:11

oxbow_lakes