Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Last active July 1, 2016 17:30
Show Gist options
  • Select an option

  • Save kevinmeredith/b1326b8c89b92807d4bff459a4e9ed35 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/b1326b8c89b92807d4bff459a4e9ed35 to your computer and use it in GitHub Desktop.
defining 'reads' in companion w/ private constructor
scala> :paste
// Entering paste mode (ctrl-D to finish)
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class Person private(age: Int)
object Person {
def build(age: Int): Option[Person] =
if (age >= 0 && age <= 125) Some(Person(age)) else None
implicit val reads: Reads[Person] =
(__ \ 'age).read[Int].map(a => Person(a))
}
@kevinmeredith

kevinmeredith commented Jul 1, 2016 •

Copy link
Copy Markdown
Author

Corrected:

...
  implicit val reads: Reads[Person] = 
   (__ \ 'age).read[Int].map(a => Person.build(a).getOrElse(throw new RuntimeException("invalid age!")))
}

@dwijnand

dwijnand commented Jul 1, 2016

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment