Scala: diverging implicit expansion for type play.api.libs.json.Writes/Reads

169 Views Asked by At

I am reading this tutorial: https://www.playframework.com/documentation/2.8.x/ScalaJson

1. In a Play/Scala controller I have the following:

def myAction  = Action.async { request: MessagesRequest[AnyContent] =>
    Future {
        case class MyData(first: Int, second: Int)

        implicit val myDataWrites = new Writes[MyData] {            
            def writes(myData: MyData) = Json.obj(
                "first"  -> myData.first,
                "second" -> myData.second
            )
        }

        Ok(Json.toJson("result" -> new MyData(1, 1)))
    }
}

When I compile from the command line, I am getting the following error:

[error] diverging implicit expansion for type play.api.libs.json.Reads[MyData]
[error] starting with method GenericFormat in trait DefaultFormat
[error]       Ok(Json.toJson("result" -> new MyData(1, 1)))
[error]                     ^
[error] one error found

It seems to me like I've been following the instructions in the tutorial:

To convert your own models to JsValues, you must define implicit Writes converters and provide them in scope.

What is missing here?

2. If I change the code to:

case class MoreData(a: Long, b: Long)
implicit val reads: Reads[MoreData] = Json.reads[MoreData]

def myAction  = Action.async(parse.json[MoreData]) { request =>
    Future {
        case class MyData(first: Int, second: Int)

        implicit val myDataWrites = new Writes[MyData] {            
            def writes(myData: MyData) = Json.obj(
                "first"  -> myData.first,
                "second" -> myData.second
            )
        }

        Ok(Json.toJson("result" -> new MyData(1, 1)))
    }
}

I get the following compilation error:

[error] diverging implicit expansion for type play.api.libs.json.Writes[(String, MyData)]
[error] starting with method GenericFormat in trait DefaultFormat
[error]       Ok(Json.toJson("result" -> new MyData(1, 1)))
[error]                     ^
[error] one error found

Again, I don't understand this. It seems like there is Writes[MyData] in the scope, and it seems like there is only one. So why doesn't it work?

And why did using parse.json[MoreData] change the error compilation from Reads to Writes?

3. Also, I wrote this code in Intellij. Which usually highlights compilation errors. For example, if I remove the implicit myDataWrites, intellij does highlight a compilation error. But with the code above it does not highlight anything.

Why is that?

0

There are 0 best solutions below