[英]Scala cake pattern with Existential Types: compile error
通过这个问题,我发现这个文章从Precog的“配置”模式。 我尝试了两个模块:
case class Pet(val name: String)
trait ConfigComponent {
type Config
def config: Config
}
trait Vet {
def vaccinate(pet: Pet) = {
println("Vaccinate:" + pet)
}
}
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 AnotherConfig {
val lastName: String
}
}
trait PetStoreModule extends ConfigComponent {
type Config <: PetStoreConfig
def sell(pet: Pet): Unit
trait PetStoreConfig {
val vet: Vet
val name: String
}
}
trait PetStoreModuleImpl extends PetStoreModule {
override def sell(pet: Pet) {
println(config.name)
config.vet.vaccinate(pet)
// do some other stuff
}
}
class MyApp extends PetStoreModuleImpl with AnotherModuleImpl {
type Config = PetStoreConfig with AnotherConfig
override object config extends PetStoreConfig with AnotherConfig {
val vet = new Vet {}
val name = "MyPetStore"
val lastName = "MyLastName"
}
sell(new Pet("Fido"))
}
object Main {
def main(args: Array[String]) {
new MyApp
}
}
但是,我得到这个编译错误:
覆盖特征Other中的Config类型,其界限<:MyApp.this.AnotherConfig;
类型配置具有不兼容的类型
Config = PetStoreConfig和AnotherConfig类型
我不清楚为什么这不起作用(Precog在示例中还使用了两个组件),有什么想法吗?
您定义了AnotherConfig两次-一次在AnotherModule中,再一次在AnotherModuleImpl中。 性状的这两个定义是不同的,并且被认为是不兼容的。 Config类型是根据前者定义的,但是在定义MyApp时,会将类型设置为后者-因此会出现错误。
您可以通过删除后者的AnotherConfig定义(由@rarry建议)或通过使后者的特征扩展前者的特性(如果您出于某种原因保留后者,例如定义额外的字段)来解决此问题。
从AnotherModuleImpl中删除AnotherConfig的定义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.