使用 Precog 配置模式的 Scala cake-pattern 编译错误

2023-12-08

继自this问题,我现在有以下内容:

case class Pet(val name: String)

trait ConfigComponent {
  type Config

  def config: Config
}

trait VetModule extends ConfigComponent {
  type Config <: VetModuleConfig

  def vet: Vet

  trait Vet {
    def vaccinate(pet: Pet)
  }

  trait VetModuleConfig {
    def extra: String
  }

}

trait VetModuleImpl extends VetModule {
  override def vet: Vet = VetImpl

  object VetImpl extends Vet {
    def vaccinate(pet: Pet) = println("Vaccinate:" + pet + " " + config.extra)
  }

}

trait AnotherModule extends ConfigComponent {
  type Config <: AnotherConfig

  def getLastName(): String

  trait AnotherConfig {
    val lastName: String
  }

}

trait AnotherModuleImpl extends AnotherModule {
  override def getLastName(): String = config.lastName
}

trait PetStoreModule extends ConfigComponent {
  type Config <: PetStoreConfig

  def petStore: PetStore

  trait PetStore {
    def sell(pet: Pet): Unit
  }

  trait PetStoreConfig {
    val petStoreName: String
  }

}

trait PetStoreModuleImpl extends PetStoreModule {
  self: VetModule with AnotherModule =>
  override def petStore: PetStore = PetstoreImpl

  object PetstoreImpl extends PetStore {
    def sell(pet: Pet) {
      vet.vaccinate(pet)
      println(s"Sold $pet! [Store: ${config.petStoreName}, lastName: $getLastName]")
    }
  }
}

class MyApp extends PetStoreModuleImpl with VetModuleImpl with AnotherModuleImpl {

  type Config = PetStoreConfig with AnotherConfig

  override object config extends PetStoreConfig with AnotherConfig {
    val petStoreName = "MyPetStore"
    val lastName = "MyLastName"
  }

  petStore.sell(new Pet("Fido"))
}


object Main {
  def main(args: Array[String]) {
    new MyApp
  }
}

我收到以下编译错误:

value petStoreName is not a member of PetStoreModuleImpl.this.Config
     println(s"Sold $pet! [Store: ${config.petStoreName}, lastName: $getLastName]")
                                   ^

这实际上是我一直在努力解决的错误。有人可以解释为什么会发生吗?目前,作为一种解决方法,我只是在每个模块实现中显式转换配置对象。


你写的should工作,但没有,因为this bug.

您可以使用多种解决方法。添加type Config = PetStoreConfig with AnotherConfig您的模块实现可能比强制转换稍微不那么令人不愉快。

更新:正如 som-snytt 在评论和回答中指出的那样,添加with PetStoreModuleImpl(关键不with PetStoreModule正如您可能期望的那样)以自我类型结尾是更好的解决方案。

作为脚注:正如 SI-7255 的评论中所讨论的,依赖对象类型演算(旨在成为“Scala 类型系统的新基础”)将解决这个“Scala 类型系统中的基本问题”。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Precog 配置模式的 Scala cake-pattern 编译错误 的相关文章

随机推荐