How do I make sure a function receives the same parameter type as the current object?

♀尐吖头ヾ 提交于 2019-12-06 16:42:15
Yuval Itzchakov

One way of achieving what you want can be done using 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)

Another way can be using 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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!