I am building a simple DSL for length operations. I want the domain operations to be extensible, so I am using them as mixins
along with the implicit
conversions for my domain components.
1. Below is my App.
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
, I marked the constructor protected, so that only subclasses can extend it and nothing else can create an instance.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, _-_)
}
Question: Is there a way to create an instance of Inches
(so that I can get all the goodies of it) while returning from the method operateOnMeasures
in my base class Length
?
I was able to resolve this by moving the Length
class inside the package object where I declared the implicit classes Inches
and Feet
.
Here is link to my working
code