Scala 解析泛型很痛苦

Scala parsing generic type is a pain

因为我在Redis中保存数据为json,当我从其他服务获取数据时,我需要将json解析为服务类型。我举一个有效的例子:

case class Item(id: Int, name: String)
object Item {
  import play.api.libs.json._

  implicit val read = Json.reads[Item]
  implicit val write = Json.writes[Item]

  def tupled = (Item.apply _).tupled
}


object RedisService {
 ...

 def get(key: String): Option[JsValue] =
   client.get(key).map(Json.parse(_))
}


object Service1 {
  val data = RedisService.get("service1")
  data match {
    case Some(json) => val items = json.as[List[Item]]
    case None =>
  }
}

..
object Service9 {
  val data = RedisService.get("service9")
  data match {
    case Some(json) => val items = json.as[List[Item]]
    case None =>
  }
}

优化类型(我正在尝试但得到隐式错误)

object RedisService {
 ...

 def get[A](key: String): Option[A] =
   client.get(key).map(x => Json.parse(x).as[A]) // no implicits found for parameter Reads[A]
}

object Service1 {
  val data = RedisService.get[List[Item]]("service1")
  data match {
    case Some(items) => // avoid using conversion in all services
    case None =>
  }
}

要修复编译器错误,您需要将该隐式参数添加到 get 的定义中,即

def get[A](key: String)(implicit format: Reads[A]): Option[A] = ...

然后对于任何实际类型 A 调用者只需要有隐式 Reads[A] 可用