Playframework: [2.4.x] Json.format returns OFormat but API says Format

Created on 2 Mar 2017  路  4Comments  路  Source: playframework/playframework

Play Version (2.5.x / etc)

2.4.3

API (Scala / Java / Neither / Both)

Scala

Expected Behaviour

Please describe the expected behaviour of the issue, starting from the first action.

  1. According to the documentation, Json.format[Foo] returns Format[Foo]

Actual Behaviour

  1. val oFormat: OFormat[Foo] = Json.format[Foo] compiles
help wanted

All 4 comments

There is no contradiction here really. Json.format[Foo] returns OFormat[Foo], which is a subtype of Format[Foo]. Which part of the documentation do you feel is incorrect?

Normally when declaring types, you would use the most general interface (Format) rather than a more specific implementation type (OFormat), but if you need to do additional manipulations like adding fields to the object, it's useful to have an OFormat, which is guaranteed to write as JsObject.

@gmethvin I agree with your general comments that when declaring types, you would use the interface rather than the implementation type. However, in this case, OFormat is not the implementation type, it is a more specific interface. Since Json.format[Foo] returns an anonymous implementation of the interface OFormat I would expect the documentation to say that it returns OFormat instead of Format.

I have also noticed that the documentation in Play 2.5 has been updated to show that it returns OFormat instead of Format (https://www.playframework.com/documentation/2.5.x/api/scala/index.html#play.api.libs.json.Json$). Therefore I think that it would be sensible for the documentation for Play 2.4 (and possibly earlier) is updated accordingly.

Okay, so the issue is not actually the documentation. The macro is typed to return Format, not OFormat: https://github.com/playframework/playframework/blob/2.4.x/framework/src/play-json/src/main/scala/play/api/libs/json/JsMacroImpl.scala#L18h. But since the code actually returns OFormat and there are no type annotations, OFormat is exposed to your code.

The change to OFormat happened in #4772. It is a backwards-compatible change, so it should be fairly straightforward to backport to 2.4.x.

I've marked this PR as "community" since this is for an experimental feature in an older release, so it's not a priority for us, but it would be a good task for a community member to address.

2.4.x is EOL

Was this page helpful?
0 / 5 - 0 ratings