Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify that an abstract method's return type is the subclass's type

Tags:

scala

How, in an abstract class, can I specify that a method's return value has the same type as the concrete class that it's a member of?

For example:

abstract class Genotype {
  def makeRandom(): Genotype  // must return subclass type
  def mutate(): Genotype      // must return subclass type
}

I'd like to say that whenever you call mutate() on a concrete Genotype class, you're sure to get back another instance of the same Genotype class.

I'd prefer not to use a type parameter in the manner of Genotype[SpecificGenotype259], since that type parameter is likely to proliferate all over the code (also, it's redundant and confusing). I'd prefer to define concrete Genotype classes by extending from various traits.

like image 396
Ben Kovitz Avatar asked Jan 10 '23 15:01

Ben Kovitz


1 Answers

You need F-bounded polymorphism:

abstract class Genotype[T <: Genotype[T]] {
  def makeRandom(): T  
  def mutate(): T      
}

class ConcreteGenotype extends Genotype[ConcreteGenotype] {
  def makeRandom(): ConcreteGenotype = ???
  def mutate(): ConcreteGenotype = ???
}
like image 169
wingedsubmariner Avatar answered Feb 02 '23 10:02

wingedsubmariner