scala - overloading a function for a bunch of types -
suppose define arithmetic operators functional types () => int, () => double etc in following manner
def + (a : () => int, b : () => int) = new (() => int) { def apply() = a() + b() } is there way avoid boiler plate code in defining similar functions possible argument type combinations? these types can built-in ones (int, long, double), user-defined ones (like currency, quantity etc), , option[t] t can before mentioned types.
def + (a : () => option[int], b : () => double) = new (() => option[double]) { // specific code factored out def apply() = a() map { _ + b() } }
you can create trait instances define concrete implementation of operations particular type. require trait implicit parameter operations , invoke these concrete implementations.
for example, check sources of scala.math.numeric.
Comments
Post a Comment