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)
}
You just need to make
IntGene
a trait. Something like this might work:And then you can instantiate the implementations by extending this trait, and the
InitStrategy
implementation. In theRandomInit
example, you could try: