如何确保函数接收与当前对象相同的参数类型?

时间:2016-10-01 16:52:33

标签: scala types type-inference self-type

abstract class A {
  protected[this] type ThisType = this.type
  protected[this] type OtherType = this.type 

  def assign(other: OtherType): ThisType
}

class B extends A {
  def assign(other: OtherType): ThisType = ???
}

class C extends A {
  def assign(other: OtherType): ThisType = ???
}

class D extends C {
  def assign(other: OtherType): ThisType = ???
}

如何确保在assign和[{1}}类型的对象中收到的其他类型也是B。例如我怎样才能有效地写出像:

B

我收到以下错误:

Error at p1 Error at p2

注意:实际上def f1(p1: A, p2: A) = p1.assign(p2) def f2[T <: A](p1: T, p2: T) = p1.assign(p2) ThisType应该是相同的,但我将它们分开,以便我可以尝试不同的选项。

1 个答案:

答案 0 :(得分:1)

使用Type Projections

可以实现实现目标的一种方法
def main(args: Array[String]): T = {
  f1(new C, new C)
}

abstract class A {
  type ThisType <: A
  def assign(other: ThisType): ThisType
}

class C extends A {
  override type ThisType = C
  override def assign(other: C): C = ???
}

class D extends C {
  override type ThisType = D
  override def assign(other: D): D = ???
}

def f1[T <: A](p1: T#ThisType, p2: T#ThisType) = p1.assign(p2)

另一种方法是使用F-bound polymorphism

abstract class A[T <: A[T]] {
  def assign(other: T): T
}

class C extends A[C] {
  override def assign(other: C): T = ???
}

def f1[T <: A[T]](p1: T, p2: T) = p1.assign(p2)