委托给更具体的上下文绑定(附加隐式参数)

pme*_*pme 5 scala implicit typeclass circe zio

我正在尝试创建一个 ZIO 模块的示例,它有两个实现:

  1. 将 YAML 与 circe-yaml 一起使用
  2. 将 HOCON 与 pureConfig 结合使用

我的通用界面如下所示:

trait Service[R] {
  def load[T <: Component](ref: CompRef): RIO[R, T]
}
Run Code Online (Sandbox Code Playgroud)

现在我的 YAML 实现看起来像:

def loadYaml[T <: Component: Decoder](ref: CompRef): RIO[Any, T] = {...}
Run Code Online (Sandbox Code Playgroud)

Decoder是特定于实现的。

现在的问题是如何从 Service 实现委托给loadYaml.

我尝试了以下方法:

val components: Components.Service[Any] = new Components.Service[Any] {

  implicit val decodeComponent: Decoder[Component] =
      List[Decoder[Component]](
         Decoder[DbConnection].widen,
           ...
        ).reduceLeft(_ or _)

   def load[T <: Component](ref: CompRef): RIO[Any, T] = loadYaml[T] (ref)
}
Run Code Online (Sandbox Code Playgroud)

这给了我:

Error:(62, 20) could not find implicit value for evidence parameter of type io.circe.Decoder[T]
       loadYaml[T] (ref)
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一目标?

我在 Github 上创建了一个示例项目:zio-comps-module

这个想法在这里描述:Decouple the Program from its Implementation with ZIO modules

pme*_*pme 3

好的,我找到了解决方案。我所要做的就是调整load函数:

def load[T <: Component](ref: CompRef): RIO[ComponentsEnv, T] = {
  loadConf[Component](ref).map { case c: T => c }
}
Run Code Online (Sandbox Code Playgroud)

首先loadConf是类型Component

第二次将 result( Component) 转换为结果类型T

这有效,但会给你丑陋的警告:

[warn] /Users/mpa/dev/Github/pme123/zio-comps-module/hocon/src/pme123/zio/comps/hocon/HoconComps.scala:37:46: abstract type pattern T is unchecked since it is eliminated by erasure
[warn]       loadConf[Component](ref).map { case c: T => c }
[warn]                                              ^
[warn] /Users/mpa/dev/Github/pme123/zio-comps-module/hocon/src/pme123/zio/comps/hocon/HoconComps.scala:37:36: match may not be exhaustive.
[warn] It would fail on the following inputs: DbConnection(_, _, _, _), DbLookup(_, _, _, _), MessageBundle(_, _)
[warn]       loadConf[Component](ref).map { case c: T => c }
[warn]                                    ^
[warn] two warnings found
Run Code Online (Sandbox Code Playgroud)

更新 - 我找到了一个消除警告的解决方案:

unchecked since it is eliminated by erasure第十次阅读警告后,我记得这可以通过添加ClassTagas Context Bound来解决。

该服务现在看起来

trait Service[R] {
  def load[T <: Component: ClassTag](ref: CompRef): RIO[R, T]
}
Run Code Online (Sandbox Code Playgroud)