Home > OS >  Constructor with derived parameters in subclasses
Constructor with derived parameters in subclasses

Time:12-20

I have a Trait Box defined and two Case Classes RedBox and BlueBox which inherit from Box. That part of my system works ok. Now, I want to create a new hierarchy of elements so a base element Token with a mutable property position could be extended to a specific kind of Box this way:

abstract class Token {
   var position: Box
}

class RedToken(position: RedBox, val marked: Boolean) extends Token {
   def test() = {
      position = RedBox()
   }
}

I need the position property to be mutable, but the compiler is throwing me "Reassignment to val". Then, if I modify the constructor signature to force the var:

class RedToken(var position: RedBox, val marked: Boolean) extends Token {
}

...I get "class RedToken needs to be abstract, since variable position in class Token of type Box is not defined". I'm not able to understand what is going on, may I have some help ? Thanks

CodePudding user response:

Use generic classes in order to make RedToken#position: RedBox

trait Box
class RedBox extends Box

abstract class Token[T <: Box] {
  var position: T
}

class RedToken(var position: RedBox) extends Token[RedBox] {
}
  • Related