我反复使用类似的代码进行JSON编组时陷入困境。片段之间的唯一区别是函数调用中的type参数。因此,我试图编写一个函数来提高代码重用性,但是似乎无法对其进行编译。我正在尝试做的事情如下所示。
/** Decode a GET response by unmarshalling its JSON payload.
* @tparam R The type of Response to unmarshall into.
* @param response The GET response to decode.
* @return Try[R] if decoding was successful, else Failure[Throwable] */
private def decodeResponse[R <: Response](response: HttpResponse): Try[R] = {
val payload = decode[R](response.text)
logger.debug(s"Decoded payload: $payload")
payload.toTry
}
如您所见,我希望将类型R
指定为返回类型的一部分和函数体的一部分。我相信是后者导致编译失败,但是我不确定如何修复它。 R
的示例为SearchResponse
,其案例类定义扩展了Response
特质。
我已经对类型参数进行了几次搜索,但是没有结果在函数体中使用类型参数。此外,我还搜索了编译时抛出的异常:
Error:(72, 28) could not find implicit value for evidence parameter of type io.circe.Decoder[R]
val payload = decode[R](response.text)
但是,所有结果都导致导致这些问题的特定库的解决方案,但是不幸的是,这对我没有用。任何帮助将不胜感激!
答案 0 :(得分:3)
decode [R]函数需要类型Decoder[R]
的隐式参数。为了使代码编译,您需要将此隐式参数添加到自己的函数中:
private def decodeResponse[R <: Response](response: HttpResponse)(implicit decoder: Decoder[R]): Try[R] = …
为某个类型参数Foo[A]
传递隐式参数A
很常见,这就是为什么他们针对这种用例提出了更简短的语法:上下文边界。
https://docs.scala-lang.org/tutorials/FAQ/context-bounds.html
就是说,当你写这个
def foo[A: Foo] = …
这等效于此:
def foo[A](implicit f: Foo[A])