case类构造函数中的继承抽象类型

时间:2015-04-16 13:59:27

标签: scala polymorphism

我正在将一些参数化的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]

我想有两个相同的case类,但是traits应该松开所有参数。这是我的尝试:

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无法编译。案例类的正确定义是什么?

1 个答案:

答案 0 :(得分:3)

您在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))