gpt4 book ai didi

scala - 案例类构造函数中继承的抽象类型

转载 作者:行者123 更新时间:2023-12-02 15:51:23 25 4
gpt4 key购买 nike

我正在将一些参数化的 F-Bounded 类型转换为抽象类型类。原来的类是:

sealed trait A[AA <: A[AA]] {
self =>
val data: String
}
case class AInst(data: String) extends A[AInst]

sealed trait B[BB <: B[BB, AA], AA <: A[AA]] {
self: BB =>
val content: AA
}
case class BInst[AA <: A[AA]](content: AA) extends B[BInst[AA], AA]

我想要两个相同的案例类,但特征应该丢失它们的所有参数。这是我的尝试:

sealed trait A2 {
self =>
type AA <: A2 {type AA = self.AA}
val data: String
}

case class A2Inst(data: String) extends A2

sealed trait B2 {
self =>
type BB <: A2 {type BB = self.BB}
type AA <: A2 {type AA = self.AA}
val content: AA
}

case class B2Inst[AHere <: A2 {type AA = AHere}](content: AHere) extends B2 {
self =>
type AA = AHere
}

val a2 = A2Inst("A2")
val b2 = B2Inst(a2)

不幸的是B2Inst无法编译。案例类的正确定义是什么?

最佳答案

您缺少 A2Inst 定义中的类型细化。

case class A2Inst(data: String) extends A2 { type AA = A2Inst }

一起:

sealed trait A2 {
self =>
type AA <: A2 {type AA = self.AA}
val data: String
}
case class A2Inst(data: String) extends A2 { type AA = A2Inst }

sealed trait B2 {
self =>
type BB <: A2 {type BB = self.BB}
type AA <: A2 {type AA = self.AA}
val content: AA
}

case class B2Inst[AHere <: A2 {type AA = AHere}](content: AHere) extends B2 {
self =>
type AA = AHere
}

val a2 = A2Inst("A2")
val b2 = B2Inst(a2)

// Exiting paste mode, now interpreting.

defined trait A2
defined class A2Inst
defined trait B2
defined class B2Inst
a2: A2Inst = A2Inst(A2)
b2: B2Inst[A2Inst] = B2Inst(A2Inst(A2))

关于scala - 案例类构造函数中继承的抽象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677024/

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