【问题标题】:Inherit from a trait when I instantiate a class当我实例化一个类时继承一个特征
【发布时间】:2015-09-10 21:40:43
【问题描述】:

这是我正在处理的代码块。它是遗传算法的基因描述。我希望它灵活并允许不同类型的基因值(int、strings、ecc.ecc.)和不同的初始化策略。现在唯一不起作用的是在IntGene的情况下,它说我需要初始化initVal,但我希望它链接到InitStrategy实现(例如RandomInit)时我实例化了这个类。如何延迟继承并从关联到实例的特征中获取实现?

abstract trait InitStrategy[T]{
  def initVal(limit:Int=0):T
}
trait RandomInit[T] extends InitStrategy[T]{
  this:{def randomFunc(limit:Int):T}=>{

  def initVal(limit:Int=0):T=this.randomFunc(limit)
  }
}

abstract trait Gene[T]

case class IntGene(v:Option[Int]=None,limit:Int=0) extends Gene[Int] with InitStrategy[Int]{

  val value=v match{
    case None => initVal(limit)
    case Some(x)=> x
  }
  def randomFunc(limit:Int):Int= (new Random).nextInt(limit)
}

【问题讨论】:

    标签: scala types traits


    【解决方案1】:

    您只需要将IntGene 设为特征。这样的事情可能会奏效:

    trait IntGene extends Gene[Int] with InitStrategy[Int]{
      val v: Option[Int]
      val limit: Int
      val value = v match {
        case None => initVal(limit)
        case Some(x)=> x
      }
      def randomFunc(limit: Int):Int= (new Random).nextInt(limit)
    }
    

    然后您可以通过扩展此 trait 和 InitStrategy 实现来实例化实现。在RandomInit 示例中,您可以尝试:

    case class RandomIntGene(v: Option[Int], limit: Int) extends IntGene with RandomInit[Int]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2018-06-02
      • 1970-01-01
      相关资源
      最近更新 更多