Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding method by return type in scala, oop solution?

I have some problem to find oop information about my problem in scala, peraphs you can help me to find a good solution, or good web/book ressources ?

I have one principal abstract class Operator :

abstract class Operator[G <: AbstractGenome, F <: GenomeFactory[G]] {
  implicit val factory: F
  def operate (genomes: IndexedSeq[G])
}

and two other inherited abstract class :

abstract class Mutation [G <: AbstractGenome, F <: GenomeFactory [G]]  
  extends Operator [G, F] {
  override def operate (genomes: IndexedSeq[G]):G
}

abstract class CrossOver [G <: AbstractGenome, F <: GenomeFactory [G]]
  extends Operator [G, F] {
  override def operate (genomes: IndexedSeq[G]) (implicit aprng : Random):IndexedSeq[G]
  }

My problem is here, i cannot override the method operate(..) with different return type when i try to instancite these abstract class, this code doesn't work.

I have already multiple lines of code which use the mutation operate() method which return an unique Genome G ... Can i conserve this OOP structure by using a wrapper, an intermediate object to catch my genome, and bypass this problem with also a generic structure ?

Thanks a lot for your lights, SR.

like image 498
reyman64 Avatar asked May 09 '26 14:05

reyman64


1 Answers

If you do not provide a return type for an abstract method Unit is used - not Any as you might have assumed. Just change the declaration in Operator to

def operate(genomes: IndexedSeq[G]): Any

This will not work in the second case though as you cannot add parameter lists when overriding methods. You will have to provide the implicit parameter via the constructor or add it to the declaration in the base class.

The easiest way to implement this would be to add a type parameter for your return type to Operation and put the implicit parameters needed for a specific instance to the constructor of your implementation, e.g.

abstract class Operator[G <: AbstractGenome, F <: GenomeFactory[G], R] {
  implicit val factory: F
  def operate (genomes: IndexedSeq[G]): R
}

class CrossOver[G <: AbstractGenome, F <: GenomeFactory [G]](implicit r: Random)
  extends Operator [G, F, IndexedSeq[G]]
like image 164
Moritz Avatar answered May 11 '26 04:05

Moritz