Search code examples
scalascala-collectionsscala-option

Behavior of map() on Options


Im trying to map a JSONObject instance into an actual instance through Play Combinators. I am able to get the desrialization work correctly. The question is on the behavior of how map() works on an Option[JSONObject].

Option1:

jsonVal: Option[JSONObject] = getAsJson(input)
jsonVal.map(JSONUtil.fromJsonString(_.toString(), Blah.jsonReads))

Doesnt work, fails to compile as the _ is not resolved correctly. Compiler couldnt find the toString() on the object.

Option2:

jsonVal: Option[JSONObject] = getAsJson(input)
jsonVal.map(_.toString()).map(JSONUtil.fromJsonString(_, Blah.jsonReads))

Works !!. Can some one tell me why the Type of the default variable is not propagated when transformation is done as part of function argument?


Solution

  • It isn't behavior of map, it's behavior of _. It's just a shortcut for the normal function expression (in this case). In the first case you have

    jsonVal.map(JSONUtil.fromJsonString(x => x.toString(), Blah.jsonReads))
    

    which obviously doesn't work, and need to write the full version

    jsonVal.map(x => JSONUtil.fromJsonString(x.toString(), Blah.jsonReads))