Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 211
ccudmore Avatar asked Oct 15 '14 13:10

ccudmore


1 Answers

Use Reads.pure

implicit val userRead: Reads[UserInfo] = (
  Reads.pure(-1L) and
  (JsPath \ "firstName").readNullable[String] and
  (JsPath \ "lastName").readNullable[String] 
)(UserInfo.apply _)
like image 139
Michael Zajac Avatar answered Nov 12 '22 09:11

Michael Zajac