如何继承通用案例 class 以重用其属性?
How to inherit generic case class to reuse its properties?
如何在 Scala 中正确实现它?
case class WithPagingJson[T](meta: PagingMetaJson, objects: Array[T])
case class CandidatesListJson extends WithPagingJson[CandidateJson]
case class OpeningsListJson extends WithPagingJson[OpeningJson]
如您所见,这些 类 是从各种 API 接收的 JSON 数据的模型。
它们都具有相同的基本结构,具有两个用于分页信息和请求对象数组的顶级属性。
编译器告诉我个例继承是被禁止的。
Scala 的正确做法是什么?
如果CandidatesJson
真的没有给WithPagingJson
添加任何东西,它可以是一个类型别名:
type CandidatesJson = WithPagingJson[CandidateJson]
不然,WithPagingJson
真的需要一个case吗class?如果你使它成为 abstract
及其所有子类型 case class
es,那么你仍然有效地获得所有相等性、哈希码等好处。
Would you mind showing the code for inheriting from abstract class?
abstract class WithPagingJson[T](val meta: PagingMetaJson, val objects: Array[T])
case class CandidatesJson(override val meta: PagingMetaJson, override val objects: Array[CandidateJson]) extends WithPagingJson[CandidateJson](meta, objects)
it seems I will have to exactly repeat whole parameters list for case class anyways? I actually was hoping to avoid exactly that.
如果它们相同,是的,但它们不一定是。也许您想将基类型改为特征
trait class WithPagingJson[T] {
val meta: PagingMetaJson
val objects: Array[T]
}
case class CandidatesJson(meta: PagingMetaJson, objects: Array[CandidateJson]) extends WithPagingJson[CandidateJson]
如何在 Scala 中正确实现它?
case class WithPagingJson[T](meta: PagingMetaJson, objects: Array[T])
case class CandidatesListJson extends WithPagingJson[CandidateJson]
case class OpeningsListJson extends WithPagingJson[OpeningJson]
如您所见,这些 类 是从各种 API 接收的 JSON 数据的模型。 它们都具有相同的基本结构,具有两个用于分页信息和请求对象数组的顶级属性。
编译器告诉我个例继承是被禁止的。 Scala 的正确做法是什么?
如果CandidatesJson
真的没有给WithPagingJson
添加任何东西,它可以是一个类型别名:
type CandidatesJson = WithPagingJson[CandidateJson]
不然,WithPagingJson
真的需要一个case吗class?如果你使它成为 abstract
及其所有子类型 case class
es,那么你仍然有效地获得所有相等性、哈希码等好处。
Would you mind showing the code for inheriting from abstract class?
abstract class WithPagingJson[T](val meta: PagingMetaJson, val objects: Array[T])
case class CandidatesJson(override val meta: PagingMetaJson, override val objects: Array[CandidateJson]) extends WithPagingJson[CandidateJson](meta, objects)
it seems I will have to exactly repeat whole parameters list for case class anyways? I actually was hoping to avoid exactly that.
如果它们相同,是的,但它们不一定是。也许您想将基类型改为特征
trait class WithPagingJson[T] {
val meta: PagingMetaJson
val objects: Array[T]
}
case class CandidatesJson(meta: PagingMetaJson, objects: Array[CandidateJson]) extends WithPagingJson[CandidateJson]