Circe:returns 密封特征 (ADT) 的特定对象的通用函数
Circe: Generic Function that returns a specific object of a Sealed Trait (ADT)
我想做这样的事情:
def loadYaml[T <: Component](ref: LocalRef): Task[T] = {
val yamlString = Source.fromResource(ref.url).mkString
val json: Either[ParsingFailure, Json] = parser.parse(yamlString)
val component = json.flatMap(_.as[T]) // this line creates the error
Task.fromEither(component)
}
解码抛出:
Error:(54, 22) could not find implicit value for parameter d: io.circe.Decoder[T]
.flatMap(_.as[T])
Component
为封印特质
用 circe 是不可能的吗?
这有效(Component
而不是 T
):
def loadYaml(ref: LocalRef): Task[Component] = {
val yamlString = Source.fromResource(ref.url).mkString
val json: Either[ParsingFailure, Json] = parser.parse(yamlString)
val component = json.flatMap(_.as[Component]) // this line creates the error
Task.fromEither(component)
}
我认为问题不在于 Decoder
,因为它与 Components
一起使用,无论如何:
implicit val decodeEvent: Decoder[Component] =
List[Decoder[Component]](
Decoder[DbConnection].widen,
Decoder[DbLookup].widen
).reduceLeft(_ or _)
正如在 documentation 上看到的 as
方法在 Json class 上,需要一个 implicit Decoder[T]
.
由于此解码器不在函数范围内,因此编译器对其进行了编译:
Error:(54, 22) could not find implicit value for parameter d: io.circe.Decoder[T]
.flatMap(_.as[T])
最简单的解决方案是将此隐式添加到方法中,并将提供它的责任留给调用者。
def loadYaml[T <: Component](ref: LocalRef)(implicit ev: Decoder[T]): Task[T] = ...
// Or even shorter (and clearer IMHO) using a context bound.
loadYaml[T <: Component : Decoder](ref: LocalRef): Task[T] = ...
我想做这样的事情:
def loadYaml[T <: Component](ref: LocalRef): Task[T] = {
val yamlString = Source.fromResource(ref.url).mkString
val json: Either[ParsingFailure, Json] = parser.parse(yamlString)
val component = json.flatMap(_.as[T]) // this line creates the error
Task.fromEither(component)
}
解码抛出:
Error:(54, 22) could not find implicit value for parameter d: io.circe.Decoder[T]
.flatMap(_.as[T])
Component
为封印特质
用 circe 是不可能的吗?
这有效(Component
而不是 T
):
def loadYaml(ref: LocalRef): Task[Component] = {
val yamlString = Source.fromResource(ref.url).mkString
val json: Either[ParsingFailure, Json] = parser.parse(yamlString)
val component = json.flatMap(_.as[Component]) // this line creates the error
Task.fromEither(component)
}
我认为问题不在于 Decoder
,因为它与 Components
一起使用,无论如何:
implicit val decodeEvent: Decoder[Component] =
List[Decoder[Component]](
Decoder[DbConnection].widen,
Decoder[DbLookup].widen
).reduceLeft(_ or _)
正如在 documentation 上看到的 as
方法在 Json class 上,需要一个 implicit Decoder[T]
.
由于此解码器不在函数范围内,因此编译器对其进行了编译:
Error:(54, 22) could not find implicit value for parameter d: io.circe.Decoder[T]
.flatMap(_.as[T])
最简单的解决方案是将此隐式添加到方法中,并将提供它的责任留给调用者。
def loadYaml[T <: Component](ref: LocalRef)(implicit ev: Decoder[T]): Task[T] = ...
// Or even shorter (and clearer IMHO) using a context bound.
loadYaml[T <: Component : Decoder](ref: LocalRef): Task[T] = ...