Play Json with Scala Trait

To be able to use trait with Play Json; you need to provide un/apply methods for the trait; and define a case class that could be instantiated.

(there might be a better approach)


import play.api.libs.json.Json
trait PaginatedTrait {
  def total: Int
  def per_page:Int
  def page: Int
  def last_page: Int

object PaginatedTrait  {

  def apply(
             total: Int,
             page: Int,
             per_page: Int,
             last_page: Int
           ): PaginatedTrait = new PaginatedRec(total, page, per_page, last_page)

  def unapply(x: PaginatedTrait): Option[(Int, Int, Int, Int)] = Some(,, x.per_page, x.last_page)

  implicit val formatPaginatedTrait = Json.format[PaginatedTrait]
  implicit val writesPaginatedTrait = Json.writes[PaginatedTrait]
  implicit val readsPaginatedTrait = Json.reads[PaginatedTrait]


import play.api.libs.json.Json

case class PaginatedRec(
                         override val total: Int,
                         override val page: Int,
                         override val per_page: Int,
                         override val last_page: Int
                       ) extends PaginatedTrait

// This might not be required
object PaginatedRec{
  implicit val paginatedTraitRecFmt = Json.format[PaginatedRec]
  implicit val paginatedTraitRecWrites = Json.writes[PaginatedRec]
  implicit val paginatedTraitRecReads = Json.reads[PaginatedRec]






scala unapply method for trait in companion object

scala apply method for trait in companion object

scala apply method in object

scala No apply function found for trait json

scala No apply function found for trait

play json No apply function found for trait



About Neil Rubens

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *