你能帮我写泛型隐式转换吗?如何编写泛型隐式转换?
我使用的是Scala 2.10.2和Spray 1.2。
这里是我有什么
// for "parameters"
implicit def ObjectIdUnmarshallerString = new Deserializer[String, ObjectId] {
def apply(value: String) =
try Right(new ObjectId(value))
catch {
case ex: Throwable => Left(MalformedContent(s"Cannot parse: $value", ex))
}
}
// for "formParameters"
implicit def ObjectIdUnmarshallerHttpEntity = new Deserializer[HttpEntity, ObjectId] {
def apply(value: HttpEntity) = ObjectIdUnmarshallerString(value.asString)
}
正如你可以看到HttpEntity->的ObjectId解串器只需使用与字符串>的ObjectId解串器。我必须为HTTP路由特征中使用的每个类复制粘贴这些代码。
所以我想如果我可以写泛型HttpEntity-> T将使用范围内可用Deserializer[String, T]
。
我尝试这样做:
implicit def GenericUnmarshallerHttpEntity[T] = new Deserializer[HttpEntity, T] {
def convertAsString(value: HttpEntity)(implicit conv: Deserializer[String, T]) = conv(value.asString)
def apply(value: HttpEntity) = convertAsString(value)
}
可悲的是它不工作。并说:
could not find implicit value for parameter conv: spray.httpx.unmarshalling.Deserializer[String,T]
def apply(value: HttpEntity) = convertAsString(value)
^
not enough arguments for method convertAsString: (implicit conv: spray.httpx.unmarshalling.Deserializer[String,T])spray.httpx.unmarshalling.Deserialized[T].
Unspecified value parameter conv.
def apply(value: HttpEntity) = convertAsString(value)
^
请问你能建议怎么做吗?
尝试'隐式def GenericUnmarshallerHttpEntity [T](隐式conv:Deserializer [String,T])= ...'并从'converAsString'移除隐式参数 –
@LuigiPlinge它帮助!您能否将您的评论粘贴为答案? – expert