gpt4 book ai didi

scala - 伴随对象的继承

转载 作者:行者123 更新时间:2023-12-02 20:46:36 24 4
gpt4 key购买 nike

我正在尝试重构一些目前看起来像这样的模型:

case class Person(name: String, age: Int)

object Person {
implicit val reads: Reads[Person] = (
(JsPath \ "name").read[String] and
(JsPath \ "age").read[Int]
)(Person.apply _)
}

对于看起来像这样的东西:

abstract class BaseModel {
val pk: String // Some stuff here that will be common
}

object BaseModel {
implicit val reads: Reads[BaseModel] // Not sure what to do here
}

这样我就可以做到这一点:

trait MyTrait[Model <: BaseModel] {

// More code here
val body: JsObject = ...
val parsed = body.validate[Model] // Error: There is no implicit value defined for Model

}


case class NewPerson extends BaseModel {...}
object NewPerson {...} // Maybe need to extend something here


class MyController extends MyTrait[NewPerson]
<小时/>

我希望每个模型都定义一个隐式读取值,但我不确定如何在抽象类的伴随对象中指示这一点。

最佳答案

没有任何语言功能会强制抽象类/伴生对一起扩展。我通过将抽象类的“同伴”作为一个特征来克服这个缺失的环节。像这样的事情:

abstract class BaseModel {
val pk: String
}

trait ModelCompanion[A <: BaseModel] { self: Singleton =>
implicit val reads: Reads[A]
}

case class Person(name: String, age: Int) extends BaseModel

object Person extends BaseModel[Person] {
...
}

不幸的是,这仍然无法说明 MyTrait (如OP中所定义)一个Model <: BaseModel有一个同伴,其中隐式 Reads[Model]可以被找寻到。同样,需要通过要求 MyTrait 手动创建链接。保存对模型伴生对象的引用。

trait MyTrait[Model <: BaseModel] {

def companion: ModelCompanion[Model]

implicit def reads: Reads[Model] = companion.reads

// More code here
val body: JsObject = ...
val parsed = body.validate[Model] // Now this would work

}

object MyTraitImpl extends MyTrait[Person] {
def companion = Person
}

关于scala - 伴随对象的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com