Question

i'm trying to import a implicit Write declaration from an embedded object into a function that produces a JSON object based on a set of case classes.

case class TestModel(test:String)

object TestModel {

  def manyToJSON(models: List[TestModel]) = {
    import writes.micro
    Json.toJson(models) 
  }

  object writes {
    implicit val micro = Json.writes[TestModel]
  }
}

unfortunately, the scala compiler complains:

No Json serializer found for type List[models.TestModel]. Try to implement an implicit Writes or Format for this type.

the fun part is, if i'm using the write object as a pure expression within the method, its working.

object TestModel {

  def manyToJSON(models: List[TestModel]) = {
    import writes.micro
    writes.micro
    Json.toJson(models) 
  }

  object writes {
    implicit val micro = Json.writes[TestModel]
  }
}

how would i have to change my code to have the implicit in scope?

Was it helpful?

Solution

the reason case class implicit is not working is that it is just a definition not value. Use case object will solve this issue like object. Consider this code:

object MainClass {


  def main(args: Array[String]) {

    TestModel.manyToJSON(Nil)
  }
}

case class TestModel(test:String)

object TestModel {

  def manyToJSON(models: List[TestModel]) = {
    import writes._
    def print(implicit x: Int) = {
      println(x)
    }

    print // print 3
  }

  object writes {
    implicit val x: Int = 3
    //implicit val x = 3 //compilation error

  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top