Dynamic inheritance in Scala -


i have abstract grandparent class named grandparent, , parent class named parentone, , several children classes named childone, childtwo, childthree, ... , on.

they written following:

abstract class grandparent {     val value: int     def print(): unit = println(value) }  class parentone extends grandparent {     override val value: int = 1 }  class childone extends parentone class childtwo extends parentone class childthree extends parentone 

what aiming provide method changing value printed in child classes to, example, 2. want method simple can.

the result creating class parenttwo following , making child classes inherit instead of parentone.

class parenttwo extends grandparent {     override val value: int = 2 } 

but know impossible, since can't dynamically change superclass. want make structure of library better, achieve task above. simplest way make it?

you wrote

what aiming provide method changing the

which i'll take method should mutate value children classes, right?

if so, use companion object of parent class store variable changed @ will:

abstract class grandparent {     def value: int     def print(): unit = println(value) }  object parent {     var mutablevalue: int = 1 }  class parent extends grandparent {     override def value: int = parent.mutablevalue }  class childone extends parent class childtwo extends parent class childthree extends parent 

example of use:

pablo-pablo@ val c = new childone()  c: childone = ammonite.$sess.cmd6$childone@4ad10ef2 pablo-pablo@ c.value  res12: int = 12 pablo-pablo@ parent.mutablevalue = 30   pablo-pablo@ c.value  res14: int = 30 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -