1

I would like to be able to provide a copy-on-update function in a parametrized, F-Bounded trait, where the value to B updated is also F-Bounded. The traits are as follows:

sealed trait A[AA <: A[AA]] {
  self: AA =>
  val data: String
}

sealed trait B[BB <: B[BB, AA], AA <: A[AA]] {
  self: BB =>
  val content: AA
}

case class BInst[BB <: B[BB,AA], AA <: A[AA]](content: AA) extends 
     B[BInst[BB, AA], AA]

In trait B, I would like to provide a function with the signature

def update[NewA <: AA](newA: NewA) : BB[BB, NewA]

so that the case class just implements

def update[NewA <: AA](newA: NewA) = copy(content = newA)

but this doesn't currently compile. What are the correct types for update in B?

edit

An example which should work (but currently doesn't):

  class A2Inst extends A[A2Inst] { val data: String = "A2Inst" }
  class A2Inst2 extends A2Inst {override val data: String = "A2INst2" }
  val a1 = new A2Inst
  val a2 = new A2Inst2
  val b = BInst(a1)
  b.update(a2)
4

1 回答 1

0

BB不采用类型参数,只需删除它们并更正输入和返回类型:

sealed trait A[AA <: A[AA]] {
  self: AA =>
  val data: String
}

sealed trait B[BB <: B[BB, AA], AA <: A[AA]] {
  self: BB =>
  def update[NewA <:A[NewA]](newA: NewA) : B[_, NewA]
  val content: AA
}

case class BInst[BB <: B[BB,AA], AA <: A[AA]](content: AA) extends 
     B[BInst[BB, AA], AA] {
  def update[NewA <: A[NewA]](newA: NewA) = copy(content = newA)
}
defined trait A
defined trait B
defined class BInst

NewA <:A[NewA]应作为输入传递以符合AA <: A[AA]. BB用 new不可能返回相同的NewA,所以你的方法会返回一些 other BB

更新你的 edit1:A2Inst2不是 F 有界的,所以你甚至不能BInst(a1),所以你应该:

class A2InstBase[T <: A2InstBase[T]] extends A[T] {val data = "a2Inst"}
class A2Inst extends A2InstBase[A2Inst]
class A2Inst2 extends A2InstBase[A2Inst2]{override val data = "a2Inst2"}
于 2015-04-15T17:24:29.720 回答