2013-08-06 60 views
2

你能帮我写泛型隐式转换吗?如何编写泛型隐式转换?

我使用的是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) 
               ^

请问你能建议怎么做吗?

+1

尝试'隐式def GenericUnmarshallerHttpEntity [T](隐式conv:Deserializer [String,T])= ...'并从'converAsString'移除隐式参数 –

+0

@LuigiPlinge它帮助!您能否将您的评论粘贴为答案? – expert

回答

2

尝试implicit def GenericUnmarshallerHttpEntity[T](implicit conv: Deserializer[String, T]) = ...convertAsString删除隐PARAM。

在问题中,apply没有要求隐式在范围内,所以它不能调用convertAsString方法。

0

你的应用功能需要有隐含穿过的转换方法

implicit def GenericUnmarshallerHttpEntity[T] = new Deserializer[HttpEntity, T] { 
    def convertAsString(value: HttpEntity)(implicit conv: Deserializer[String, T]) = conv(value.asString) 

    def apply(value: HttpEntity)(implicit conv: Deserializer[String, T]) = convertAsString(value) 
} 
+0

不幸的是我尝试过。编译器说'对象创建不可能,因为方法适用于类型(v1:spray.http.HttpEntity)的特性Function1 spray.httpx.unmarshalling.Deserialized [T]没有定义 (请注意T1不匹配spray.http.HttpEntity ) implicit def GenericUnmarshallerHttpEntity [T] = new Deserializer [HttpEntity,T] { ^'' – expert