Search code examples
scalafor-comprehensionjson4s

How to "de-sugar" this Scala statement?


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 ?


Solution

  • 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)