title: scala: define a Type that has defined a certain implicit
body: <p>I want to define a function with a generic type T, in which for T there's an implicit implementation of a certain method</p>
  
  <p>In fact I'm trying to achieve the following:</p>
  
  <p>I have very repetitive code like this:</p>
  
  <pre><code>def update(id: Long) = CORSAction { implicit request =&gt;
    request.body.asJson.map { json =&gt;
      json.asOpt[Wine].map { wine =&gt;
        wine.copy(id=Id(id)).update.fold(
          errors =&gt; JsonBadRequest(errors),
          wine =&gt; Ok(toJson(wine).toString)
        )
      }.getOrElse       (JsonBadRequest("Invalid Wine entity"))
    }.getOrElse         (JsonBadRequest("Expecting JSON data"))
  }
  </code></pre>
  
  <p>So, checking if it's a valid json and then parsing it, is a very common task that I'd like to encapsulate in a function.</p>
  
  <p>For the wine type I have defined an implicit JsonWineFormatter which implements a writes and reads method to parse from json and render as json a wine object</p>
  
  <pre><code>object WineFormatter {
  
    implicit object JsonWineFormatter extends Format[Wine] {
  
      def writes(o: Wine): JsValue = {
        toJson( Map(
          "id"          -&gt; toJson(o.id),
      [...]
  
      def reads(j: JsValue): Wine = {
        Wine(
          id = (j \ "id").as[Option[Pk[Long]]] 
      [...]
  </code></pre>
  
  <p>So I'm trying to define a generic method like this:</p>
  
  <pre><code>def parse[T](implicit request: Request[AnyContent]): Option[T] = {
    request.body.asJson.map { json =&gt;
      json.asOpt[T].map { entity =&gt;
        entity
      }
    }
  }
  </code></pre>
  
  <p>But I get the followgin error:</p>
  
  <p><strong>No Json deserializer found for type T. Try to implement an implicit Reads or Format for this type.</strong></p>
  
  <p>I need to specify that the generic type T needs and implicit Reads...</p>
  
  <p>Do you know how to achieve it?</p>
  
  <p>--</p>
  
  <p>edit: I tried with the following:</p>
  
  <pre><code>import play.api.libs.json.JsValue
  type EntityWithJsonFormatter[T] = T {def reads(j: JsValue): T}
  
  def parse[T: EntityWithJsonFormatter](request: Request[AnyContent]): Option[T] = {
    request.body.asJson.map { json =&gt;
      json.asOpt[T].map { entity =&gt;
        entity
      }
    }
  }
  </code></pre>
  
  <p>But obviously, it's not T the one supossed to implement reads, instead there should be an implicit object that implements it. I don't know how to specify that in a type...</p>