0

LINQ-style queries in Scala with json4s look as follows:

val jvalue = parse(text) // (1)
val jobject = for(JObject(o) <- jvalue) yield o // (2)

I do not understand exactly how (2) works. How would you de-sugar this for-statement ?

Michael
  • 41,026
  • 70
  • 193
  • 341
  • 1
    Be aware that filter on a JValue traverses the full JSON tree. So you are not just matching the `jvalue`, but all nodes below too. In other words it does a search on the JSON tree. – Stefan Ollinger Mar 29 '14 at 22:11

1 Answers1

2

for-comprehensions of the form

for(v <- generator) yield expr

are translated into

generator.map(v => expr)

When you have a pattern match on the left, then any input values which do not match the pattern are filtered out. This means a partial function is created containing the match, and each input argument can be tested with isDefinedAt e.g.

val f: PartialFunction[JValue, JObject] = { case o@JObject(_) => o }
f.isDefinedAt(JObject(List[JField]()))   //true
f.isDefinedAt(JNull)                     //false

This means your example will be translated into something like:

PartialFunction[JValue, List[JField]] mfun = { case JObject(o) -> o }
var jobject = jvalue.filter(mfun.isDefinedAt(_)).map(mfun)
Lee
  • 142,018
  • 20
  • 234
  • 287