首页 > 解决方案 > 从父类创建子实例

问题描述

我正在为长度操作构建一个简单的 DSL。我希望域操作是可扩展的,所以我将它们与我的域组件mixins的转换一起使用。 1. 下面是我的应用程序。implicit

package com.shasank.funWithLengths

object LengthAdditionApp extends App{

  val length1 = 11 inches
  val length2 = 15 inches
  val length3 = 2 feet

  println(length1)
  println(length2)
  println(length3)
  println(length1 + length2) // all ok
  println(length1 + length3) // all ok
  println(length3 - length1) // all ok
  println(length1 + length2 + length2) // this breaks since object returned from first operation doesn't have adder

}
  1. 下面是我的基类。我本来希望这是抽象的,但由于我找不到创建子类实例的方法Inches,我将构造函数标记为受保护,这样只有子类可以扩展它,其他任何东西都不能创建实例。
package com.shasank.funWithLengths

class Length protected(val measure: Int, val unit: String) {

  private def convertToInches(length: Length)= length.unit match {
    case "feet" => length.measure * 12
    case "inches" => length.measure
  }

  protected def operateOnMeasures(other: Length, op: (Int,Int) => Int): Length ={
    val thisInches = convertToInches(this)
    val otherInches = convertToInches(other)
    val operatedMeasure = op(thisInches,otherInches)
    new Length(operatedMeasure, "inches")  // object created does not have adder & subtracter capabilities
  }

  override def toString = {
    val measureInInches = convertToInches(this)
    val (feetMeasure, inchesMeasure) = BigInt(measureInInches) /% 12
    val feetMeasureString = s"$feetMeasure feet and"
    val inchesMeasureString = s"$inchesMeasure inches"
    s"$feetMeasureString $inchesMeasureString"
  }

}
  1. 以下是我的域组件。
package com.shasank

package object funWithLengths {
  implicit class Inches(measure: Int) extends Length(measure, "inches") with Adder with Subtracter {
    def inches = this
  }
  implicit class Feet(measure: Int) extends Length(measure, "feet") with Adder with Subtracter {
    def feet = this
  }
}
  1. 以下是我的域名运营商。
package com.shasank.funWithLengths

trait Adder extends Length {
  def +(other: Length) = super.operateOnMeasures(other, _+_)
}
package com.shasank.funWithLengths

trait Subtracter extends Length {
  def -(other: Length) = super.operateOnMeasures(other, _-_)
}

问题:有没有办法在从我的基类中的方法返回时创建一个实例Inches(以便我可以获得它的所有优点)?operateOnMeasuresLength

标签: scalaoopfunctional-programmingaopdsl

解决方案


我可以通过Length在我声明隐式类InchesFeet.
这是我的工作 代码的链接


推荐阅读