简体   繁体   English

如何在特征中定义隐式写入

[英]How to define implicit Writes in trait

I have multiple case classes representing values in DB for ex User which saves user based properties like name / age / address and CallLog which saves timestamp / status_of_call 我有多个案例类代表ex User的DB中的值,该类可保存基于用户的属性,如姓名/年龄/地址,以及CallLog,可保存时间戳/ status_of_call

What i want to achieve 我想实现的目标

I want to have a helper function which accepts list of models and checks if the list is empty then returns "error" otherwise should return json array of the list. 我想有一个辅助函数,该函数接受模型列表并检查列表是否为空,然后返回“错误”,否则应返回列表的json数组。

My Approach 我的方法

I want to have a trait which groups certain models in it and the helper method will accept either the trait or List of it in order to check or may be have a generic which implements the trait. 我想拥有一个特征,该特征将其中的某些模型分组,并且辅助方法将接受该特征或其列表以进行检查,或者可能具有实现该特征的泛型。

Problem 问题

Since implicit writes are tightly coupled with the model class, compiler throws the error on the line Json.toJson(list) 由于隐式写入与模型类紧密耦合,因此编译器在Json.toJson(list)行上引发错误。

Things i have tried Kept implicit in trait and got recursive type error 我尝试过保持特征隐式的东西并得到递归类型错误

I am scala noob pardon me if this sounds silly Thanks in advance 如果这听起来很愚蠢,我是scala noob,请原谅

Since User, CallLog, etc. will be serialized differently, Each Writes[T] will be different for each implementation of your Model trait, so a Writes[Model] has to know about the implementation it is trying to serialize. 由于User,CallLog等的序列化方式不同,因此对于Model特质的每个实现,每个Writes [T]都会有所不同,因此Writes [Model]必须知道它要序列化的实现。

It is therefore not possible to have it part of the Model trait, because this information isn't known yet when you define it. 因此,不可能将其作为模型特征的一部分,因为在定义它时尚不知道此信息。

A workaround in your case would be to define your Writes[Model] in the scope of your helper function instead. 在您的情况下,一种解决方法是改为在辅助函数的范围内定义Writes [Model]。

An implementation of your helper function could be like this : 您的辅助函数的实现可能是这样的:

import play.api.libs.json.{JsValue, Json, Writes}

sealed trait Model

case class User(name: String, age: String, address: String) extends Model
object User {
  implicit val userWrites = Json.writes[User]
}
case class CallLog(timestamp: String, status_of_call: String) extends Model
object CallLog {
  implicit val callLogWrites = Json.writes[CallLog]
}

implicit val modelWrites = new Writes[Model] {
  override def writes(o: Model): JsValue = o match {
    case u: User => Json.toJson(u)
    case cl: CallLog => Json.toJson(cl)
  }
}

def helper(models: Model*): Either[JsValue, String] = models match {
  case Nil => Right("Error")
  case _ => Left(Json.toJson(models))
}

helper(User("John", "32", "..."))
helper(User("John", "32", "..."), CallLog("now", "In progress"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM