Search code examples
jsonscalaplayframeworkplayframework-json

Constant value in Scala Play JSON Reads


I'd like to use a constant value when constructing an object via a JSON read.

For example the class would be:

case class UserInfo(
  userId: Long = -1, 
  firstName: Option[String] = None,
  lastName:  Option[String] = None
)

And the read would be:

   implicit val userRead: Reads[UserInfo] = (
      (JsPath \ "userId").read[Long] and
      (JsPath \ "firstName").readNullable[String] and
      (JsPath \ "lastName").readNullable[String] 
    )(UserInfo.apply _)

But I don't want to have to specify the value for userId in the JSON object. How would I go about coding the Reads so that the value of -1 is always created in the UserInfo object without specifying it in the JSON object being read?


Solution

  • Use Reads.pure

    implicit val userRead: Reads[UserInfo] = (
      Reads.pure(-1L) and
      (JsPath \ "firstName").readNullable[String] and
      (JsPath \ "lastName").readNullable[String] 
    )(UserInfo.apply _)