我有一个用于将 json 解码器注入为项目组件依赖项的特征:
trait JsonDecoder {
def apply[T](s: String): Option[T]
}
当我尝试用它来实现它时Circe https://circe.github.io/circe/:
import io.circe.generic.auto._
import io.circe.parser.decode
case class CirceJsonDecoder() extends JsonDecoder {
def apply[T](s: String): Option[T] = {
decode[T](s).fold(_ => None, s => Some(s))
}
}
and run:
case class C()
def test(d: JsonDecoder) = d[C]("{}")
test(CirceJsonDecoder())
它不会编译并出现错误:
could not find implicit value for parameter decoder: io.circe.Decoder[T]
我尝试添加ClassTag
, TypeTag
or WeakTypeTag
上下文边界为T
但它仍然找不到隐含的价值Decoder
.
我无法添加Decoder
上下文绑定或隐式参数JsonDecoder.apply
因为使用它的组件不应该知道实现细节。
我应该如何提供隐式io.circe.Decoder
?可能有某种方法可以从中获取它TypeTag
?
我认为你不能以任何涉及 circe 的方式影响你的 apply 方法签名。
如果可以的话那就意味着circe.auto_
能够在任何类型 T 的范围内引入隐式解码器,但这是不正确的。
AFAIK,没有比添加隐式更好的类型注释了Decoder
向您的函数发出信号,表明它实际上知道如何处理这种类型(如果您愿意,可以使用T: Decoder
版本,但最终是一样的)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)