[2.4.6-Scala] JsResult; match or fold ?

214 views
Skip to first unread message

Gervais Blaise

unread,
Feb 2, 2016, 6:45:42 AM2/2/16
to play-framework
Hi there,

While reading the documentation about Json. There is one example who use `JsResult.fold` to process the `errors` or json object, in the next page, there is another example who use pattern matching against `JsSuccess` and `JsError`. This is, no doubt a trivial or troll questions but. Is it a recommandation or best practices to use `fold` or pattern matching ?

Thanks

Daniel Manchester

unread,
Feb 8, 2016, 11:28:31 PM2/8/16
to play-framework
Hi,

I haven't worked with JsResult before, but it looks like an either-or type (an instance is either a JsSuccess or a JsError), somewhat similar to a Scala Option (either a Some or a None).

Option offers a fold() method, too, which has been criticized for a lack of readability. See, for example, "Option.fold() considered unreadable". I imagine those criticisms would also apply to JsResult's fold().

In fact, the authors of Play's "JSON basics" documentation (what I believe you were looking at) pretty much admit there's a readability issue: there's no programmatic reason to specify the argument names as they do...

    fold(invalid = ..., valid = ...)

...so I presume they did it to reduce confusion.

So yeah, I think pattern matching would be better. Or, maybe you could do some kind of JsResult.map(...).getOrElse(...) construction, as the above blog post does with Option?

Dan
Reply all
Reply to author
Forward
0 new messages