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.
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 = ???
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With