Scala路径相关返回类型案例类复制

时间:2014-04-02 09:04:23

标签: scala

对以下内容进行了一次清醒:

abstract class A {
  def withName(name: String): this.type
}

case class B(name: String) extends A {
  def withName(name: String): this.type = copy(name = name.reverse)
}

case class C(name: String) extends A {
  def withName(name: String): this.type = copy(name = name.toLowerCase)
}

基本上我希望B和C中的方法返回与它们相同的类型。

2 个答案:

答案 0 :(得分:4)

当然,你也可以使用类型成员来做同样的事情:

abstract class A {
  type R <: A
  def withName(name: String): R
}

case class B(name: String) extends A {
  type R = B
  def withName(name: String): R = copy(name = name.reverse)
}

答案 1 :(得分:1)

两种可能的解决方案:

角色:

abstract class A {
  def withName(name: String): this.type
}

case class B(name: String) extends A {
  def withName(name: String): this.type = copy(name = name.reverse).asInstanceOf[this.type]
}

case class C(name: String) extends A {
  def withName(name: String): this.type = copy(name = name.toLowerCase).asInstanceOf[this.type]
}

F-有界多态性:

abstract class A[T <: A[_]] {
  def withName(name: String): T
}

case class B(name: String) extends A[B] {
  def withName(name: String): B = copy(name = name.reverse)
}

case class C(name: String) extends A[C] {
  def withName(name: String): C = copy(name = name.toLowerCase)
}