我刚开始涉猎Scala,现在想了解是否有办法在Scala中表达深度部分类型(递归类型)?
###################### 更新 ######################
我的目标是获取一个现有的case class并以某种方式“版本化”它,使其递归地添加到每个字段,即使是在深度嵌套的级别。
例如,假设我已经定义了这些类:
case class A(p1: Int, p2: Int, ..)
case class B(p1: Map[String, A])
case class C(param1: String, param2: String, param3: Option[B])
我想要对C进行版本控制,这意味着对于每个参数类型(递归地),我都希望添加一个可选的
version: Int
。我看到的一种朴素方法是定义一个新类
VersionedValue
,然后手动重新定义所有现有类型以适应此更改。例如,它可能看起来像这样:
case class VersionedValue [A](value: A, version: Option[Int])
case class A(p1: VersionedValue[Int], p2: VersionedValue[Int])
case class B(p1: Map[String, VersionedValue[A]])
case class C(p1: VersionedValue[String],
p2: VersionedValue[String],
p3: Option[B])
在使用 TypeScript 一段时间之后,通常会看起来像这样:
/**
* the VersionedDeepPartial<T> will recursively iterate through
* each of the "keys" (or attributes) and for each creates a new
* object that adds a version field. The value attribute will hold
* what was originally the type for the key.
*/
export type VersionedDeepPartial<T> = {
[P in keyof T]?: {value: VersionedDeepPartial<T[P]>; version?:number}
};
// So if I had an interface (in typescript) looking like:
interface A {
p1: number,
p2: number,
}
interface B {
[key: string]: A
}
interface C {
p1: String,
p2: String,
p3: B
}
/**
* Note that interface C does not define any versioning attribute to
* its fields. But by wrapping the type within the
*/
VersionedDeepPartial<T>
const partialFoo: VersionedDeepPartial<C> = {
p1: { value: "asdf", version: 1 },
p2: { value: "asdf" },
p3: {
"somekey": {
p1: {value: 1, version: 1},
p2: {value: 2}
}
}
基本上,我想通过递归遍历现有类型/类定义并向其中“注入”版本控制来定义一个新的类型。
我已经阅读/浏览了关于此主题的说明,但没有成功。在Scala中是否可能表达这个想法?
Mirror
?)。 - ziggystar