Pregunta

I want to make a copy of B, however I do not want to repeat the copying in the subclass (B) that goes on in the superclass (A).

The solution below is what I cooked up. But I don't like it because it is not a copy constructor and because it is mutating state (vars everywhere).

Scala allows direct call to super only from the primary constructor so I had no idea how to create a copy constructor for B without repeating the copying code present in the superclass (A).

Any suggestions on how to implement a DRY copy constructor or a more elegant way to copy?

class A {
  var fieldA=1
  def copyFieldsInto(a:A):Unit={
    a.fieldA=fieldA
  }
}

class B extends A{
  var fieldB=2
  def copyFieldsInto(b:B):Unit=
  {
    super.copyFieldsInto(b)
    b.fieldB=fieldB
  }
}

object Test extends App{
  println("hello")
  val b=new B
  b.fieldA=3
  b.fieldB=4
  val b_copy=new B
  b.copyFieldsInto(b_copy)
  println(b.fieldB,b.fieldA)
  println(b_copy.fieldB,b_copy.fieldA)
}

this will print :

hello 
(4,3) 
(4,3)
¿Fue útil?

Solución

If I understand you correctly, then this is what you want?

class A(val aVal: Int) {
  def this(a:A)={
    this(a.aVal)
  }
}

class B(aVal:Int, val bVal:Int) extends A(aVal){
  def this(b:B) = {
    this(b.aVal, b.bVal)
  }
}

object Test extends App{
  println("hello")                                
  val b=new B(3,4)                                
  val b_copy=new B(b)                             
  println(b.bVal,b.aVal)                          
  println(b_copy.bVal,b_copy.aVal)        
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top