且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scala:在父方法中维护子类?

更新时间:2023-11-18 15:28:04

一种方法是参数化父对象:

 abstract class Parent[T <: Parent[T]] {
    def something(arg: Foo): T
 }

 class Child(val foo: String) extends Parent[Child] {
    def something(arg: String) = return new Child(arg)
 }

有时候,您也可以使用this.type:

class Parent {
  def something(arg: Foo): this.type = this
}
class Child {
   override def something(arg: Foo) = this
}

但是后一种方法仅在您要返回的全部是this时才有效(this.type不是ParentChild,而是仅具有一个实例的特定类型-this)./p>

When you have a parent:

abstract class Parent {
   def something(arg: ???): Parent = ???
}

and

class Child extends Parent {}

I would like

val updatedChild = new Child().something(...)

updatedChild to be of type Child and not of type Parent, is it possible ?

One way to do it, is to parametrize the parent:

 abstract class Parent[T <: Parent[T]] {
    def something(arg: Foo): T
 }

 class Child(val foo: String) extends Parent[Child] {
    def something(arg: String) = return new Child(arg)
 }

Sometimes, you can also get away with using this.type:

class Parent {
  def something(arg: Foo): this.type = this
}
class Child {
   override def something(arg: Foo) = this
}

But the latter method only works if all you ever want to return is this (this.type is not Parent or Child, but a specific type that only has one instance - this).