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?
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.
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.
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.
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.
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!
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With