scala – 如何指定抽象方法的返回类型是子类的类型

在抽象类中,我如何指定方法的返回值与它所属的具体类具有相同的类型?

例如:

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())

这种方法很容易适应未来的修改和扩展,例如向GenotypeSystem添加其他类型.

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...