Scala 如何避免子类的伴随对象中的代码重复

Scala 如何避免子类的伴随对象中的代码重复,scala,Scala,我的Scala代码中有以下模式: class A(x: Int) object A { def apply(x: Int, y: Int) = new A(x + y) } class B(x: Int) extends A(x) object B { def apply(x: Int, y: Int) = new B(x + y) } 除了它们构造的对象的类之外,apply方法完全相同。我希望避免这种代码重复,特别是因为在我的实际代码中,我有几个apply方法,它们要长得多 我怎样

我的Scala代码中有以下模式:

class A(x: Int)
object A {
  def apply(x: Int, y: Int) = new A(x + y)
}

class B(x: Int) extends A(x)
object B {
  def apply(x: Int, y: Int) = new B(x + y)
}
除了它们构造的对象的类之外,apply方法完全相同。我希望避免这种代码重复,特别是因为在我的实际代码中,我有几个apply方法,它们要长得多

我怎样才能做到这一点?如何删除此代码重复

我想到了这样的事情:

class A(x: Int)
class B(x: Int) extends A(x)

trait C[T <: A] {
  def apply(x: Int, y: Int) = new T(x + y)
}

object A extends C[A]
object B extends C[B]
A类(x:Int)
B类(x:Int)扩展了A(x)

特征C[T我将提出以下解决方案:

class A(x: Int)
class B(x: Int) extends A(x)

trait C[+T <: A] {
  def apply(x: Int, y: Int) = create(x + y)
  protected def create(x: Int): T
}

object A extends C[A] {
  override protected def create(x: Int) = new A(x)
}
object B extends C[B] {
  override protected def create(x: Int) = new B(x)
}
A类(x:Int)
B类(x:Int)扩展了A(x)

特质C[+T在特定情况下,你可以做如下事情

class A(x: Int) {
  def this(x: Int, y: Int) = this(x + y)
}
class B(x: Int) extends A(x)

这真的不能解决代码重复问题,不是吗?它避免了“x+y”的重复,这是唯一一个不能在构造函数上真正抽象的重复逻辑。如果您愿意将
A
B
设为
case类
es,您可以调用(生成的)
应用
C
中伴生对象的方法。
class Adder[T](f: Int => T) {
  def apply(x: Int, y: Int) = f(x + y)
}

class A(x: Int)
object A extends Adder(new A(_))

class B(x: Int) extends A(x)
object B extends Adder(new B(_))