Inherit from a trait when I instantiate a class

58 Views Asked by At

This is the block of code I'm working on. It's the gene description of a genetic algorithm. I want it to be flexible and allow for different type of gene values (int, strings, ecc. ecc.) and different initialization strategies. Right now the only thing that doesn't work is that in the case of IntGene it says that I need to initialize initVal but I want it to be linked to a InitStrategy implementation (for example RandomInit) when I instantiate the class. How can I delay the inheritance and take the implementation from the trait I associate to the instance?

abstract trait InitStrategy[T]{
  def initVal(limit:Int=0):T
}
trait RandomInit[T] extends InitStrategy[T]{
  this:{def randomFunc(limit:Int):T}=>{

  def initVal(limit:Int=0):T=this.randomFunc(limit)
  }
}

abstract trait Gene[T]

case class IntGene(v:Option[Int]=None,limit:Int=0) extends Gene[Int] with InitStrategy[Int]{

  val value=v match{
    case None => initVal(limit)
    case Some(x)=> x
  }
  def randomFunc(limit:Int):Int= (new Random).nextInt(limit)
}
1

There are 1 best solutions below

0
On BEST ANSWER

You just need to make IntGene a trait. Something like this might work:

trait IntGene extends Gene[Int] with InitStrategy[Int]{
  val v: Option[Int]
  val limit: Int
  val value = v match {
    case None => initVal(limit)
    case Some(x)=> x
  }
  def randomFunc(limit: Int):Int= (new Random).nextInt(limit)
}

And then you can instantiate the implementations by extending this trait, and the InitStrategy implementation. In the RandomInit example, you could try:

case class RandomIntGene(v: Option[Int], limit: Int) extends IntGene with RandomInit[Int]