scala - 从父类创建子实例
问题描述
我正在为长度操作构建一个简单的 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
}
- 下面是我的基类。我本来希望这是抽象的,但由于我找不到创建子类实例的方法
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"
}
}
- 以下是我的域组件。
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
}
}
- 以下是我的域名运营商。
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
(以便我可以获得它的所有优点)?operateOnMeasures
Length
解决方案
我可以通过Length
在我声明隐式类Inches
和Feet
.
这是我的工作
代码的链接
推荐阅读
- python - 大熊猫在正则表达式后删除空间
- python - Spark 3.0.0 创建 SparkSession 时出错:pyspark.sql.utils.IllegalArgumentException:
- javascript - 实现一个 Vue.js 组件,以便将元素定义为
- cassandra - Cassandra 3.11,按列表过滤结果(搜索替代品)
- postgresql - PostgreSQL - dblink_exec statement_timeout
- c# - Xamarin Forms 嵌套 flex 布局与其他控件无法正确呈现
- javascript - 如何将放置在reactjs中的json对象内的图像发布到spring boot后端rest api
- python - 使用 scikit learn 在 python 中进行管道和交叉验证
- .net - 如何自动启动使用 Msix 打包的应用程序?
- key-value - etcd 是否将其 key-value 数据直接存储在 Raft 日志中?