因為我在 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 =>
}
}
uj5u.com熱心網友回復:
要修復編譯器錯誤,您需要將該隱式引數添加到getie的定義中
def get[A](key: String)(implicit format: Reads[A]): Option[A] = ...
然后對于任何實際型別A,呼叫者只需要隱式 Reads[A] 可用
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422300.html
標籤:
上一篇:scala2.13:型別IndexedSeq采用型別引數
下一篇:scala型別擦除-匹配案例類
