English 中文(简体)
B. 回归新的相应类别儿童物体的陈情学分级方法
原标题:Scala abstract class method that returns a new corresponding class child object

I have the following class in my mind:

abstract class MyClass (data: MyData) {

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

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

}

然而,抽象的班级不能上调,因为“新日志”(工艺)

最佳回答

怎样做这样的事情? <代码>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
}

信贷:IttayD's second Update to his 问题

问题回答

To completly avoid implementing almost identical method in all subclasses you would need to use reflection. I guess that would be your last resort if you have chosen Scala. So here is how to minimize the repetitive code:

// 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(_))

这样,你就只能重复最短的碎块,用于对子级进行即时处理。





相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签