【问题标题】:Scala parsing generic type is a painScala解析泛型类型很痛苦
【发布时间】:2022-01-26 18:14:57
【问题描述】:

因为我在 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 =>
  }
}

【问题讨论】:

    标签: scala generics playframework


    【解决方案1】:

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

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

    那么对于任何实际类型 A,调用者只需要隐式 Reads[A] 可用

    【讨论】:

    • 这就是解决方案,谢谢:D 我想我需要深入了解Implicits
    猜你喜欢
    • 1970-01-01
    • 2019-06-30
    • 2014-08-18
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多