在抽象类中,我如何指定方法的返回值与它所属的具体类具有相同的类型?
例如:
abstract class Genotype { def makeRandom(): Genotype // must return subclass type def mutate(): Genotype // must return subclass type }
我想说,每当你在一个具体的Genotype类上调用mutate()时,你肯定会回到同一Genotype类的另一个实例.
我不希望以Genotype [SpecificGenotype259]的方式使用类型参数,因为该类型参数可能在整个代码中泛滥(同样,它是多余的和令人困惑的).我更喜欢通过扩展各种特征来定义具体的基因型类.
解决方法
我建议针对这种情况使用参数化模块:
trait GenotypeSystem { type Genotype <: GenotypeLike trait GenotypeLike { def makeRandom(): Genotype def mutate(): Genotype } } // Example implementation object IntGenotypeSystem extends GenotypeSystem { case class Genotype(x: Int) extends GenotypeLike { def makeRandom() = copy(x = Random.nextInt(10)) def mutate(): Genotype = copy(x = x + Random.nextInt(3) - 1) } } // Example abstract usage def replicate(gs: GenotypeSystem)(g: gs.Genotype,n: Int): Seq[gs.Genotype] = Seq.fill(n)(g.mutate())