加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:53:47 所属栏目:安全 来源:网络整理
导读:在抽象类中,我如何指定方法的返回值与它所属的具体类具有相同的类型? 例如: abstract class Genotype { def makeRandom(): Genotype // must return subclass type def mutate(): Genotype // must return subclass type} 我想说,每当你在一个具体的Genoty
在抽象类中,我如何指定方法的返回值与它所属的具体类具有相同的类型?

例如:

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添加其他类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读