我编写了一个特征,以利用现有的JSON Writes实例将自身序列化以查询字符串参数的能力混入类中。为了使用Writes实例作为参数,我需要知道此特征混合到的类型。我使用类型参数(应该是类本身)和自类型注释来得到。我想知道是否有这样做的DRYer方式,不需要type参数?
这是我的代码:
trait ConvertibleToQueryString[T] {
this: T =>
/** Transformation of field names in obj to query string keys */
def objToQueryStringMapping: Map[JsPath, JsPath] = Map.empty
/**
* Convert a model to a Map, for serialization to a query string, to be used
* in a REST API call.
* @param writes writer for `obj`
* @return
*/
def toQueryStringMap(implicit writes: Writes[T]): Map[String, String] = {
// Get a map of key -> JsValue from obj
val mapObj = Json.toJson(this).transform(moveKeys(objToQueryStringMapping)).get.value
// Convert the JsValue values of the map to query strings
mapObj.mapValues(jsValueToQueryStringValue).filter(_._2.nonEmpty).toMap
}
}
,其用途如下:
case class MyClass(param1: String, param2: Int) extends ConvertibleToQueryString[MyClass]
,最后一个类型参数是令我烦恼的事情。它完全不受限制,但实际上应该只是“我混入的类的类型”。有没有办法表达这一点?
为什么不使用pimp- encrich -我的图书馆模式:
implicit class ConvertibleToQueryString[T: Writes](x: T) {
def objToQueryStringMapping: Map[JsPath, JsPath] = Map.empty
def toQueryStringMap: Map[String, String] = {
// Get a map of key -> JsValue from obj
val mapObj = Json.toJson(x).transform(moveKeys(objToQueryStringMapping)).get.value
// Convert the JsValue values of the map to query strings
mapObj.mapValues(jsValueToQueryStringValue).filter(_._2.nonEmpty).toMap
}
}
现在,您根本不需要extends ...
要序列化的类。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句