Scala is an abstract class method that returns the new corresponding class child

I have the following class:

abstract class MyClass (data: MyData) {

  def update(): MyClass = {
    new MyClass(process())
  }

  def process(): MyData = {
    ...
  }

}

However, abstract classes cannot be created, so the string new MyClass(process())is an error. My question is: is there a way to tell the compiler that in the case of each of the MyClass child classes, I want to create an object of this particular child class? It seems redundant to write this awhole method in all child classes. Playing with parameters like a class or method, I could not achieve this.

+5
source share
2 answers

- ? MyClass . , , Self.

trait MyClass[+Self <: MyClass[Self]] {
  def update(): Self = {
    makeNew(process())
  }

  def process(): MyData = {
    // ...
  }

  protected def makeNew(data: MyData): Self
}

class Concrete0 extends MyClass[Concrete0] {
  protected def makeNew(data: MyData) = new Concrete0
}

class RefinedConcrete0 extends Concrete0 with MyClass[RefinedConcrete0] {
  override protected def makeNew(data: MyData) = new RefinedConcrete0
}

: IttayDs .

+6

, . , , Scala. , :

// additional parameter: a factory function
abstract class MyClass(data: MyData, makeNew: MyData => MyClass) {

  def update(): MyClass = {
    makeNew(process())
  }
  def process(): MyData = {
    ...
  }
}

class Concrete(data: MyData) extends MyClass(data, new Concrete(_))

, .

+3

All Articles