Scala DSL for currency-related operations
Posted: | Categories: Programming, Scala | Tags: DSL, Implicit
A simple internal DSL in Scala for money-related operations
Source code: Scala DSL for money-related operations
This Domain-Specific Language (DSL) lets you perform operations among different currencies, by transparently doing all internal conversions. The conversion map is injected implicitly by the client code.
Usage Example
Here’s a simple usage example:
import com.lambdista.money._
import com.lambdista.money.Currency._
object Main {
def main(args: Array[String]): Unit = {
val conversion: Conversion = Map(
(GBP, EUR) -> 1.270,
(EUR, USD) -> 1.268,
(GBP, USD) -> 1.611
)
implicit val converter = Converter(conversion)
val sumAndConversion1 = 100.001(USD) + 200(EUR) to GBP
println(s"sumAndConversion1: $sumAndConversion1")
val sumAndConversion2: Money = 100(USD) + 210.4(EUR) to EUR
println(s"sumAndConversion2: $sumAndConversion2")
val sum = 100.001(USD) + 200(EUR)
val simpleConversion = sum(GBP)
println(s"simpleConversion: $simpleConversion")
val sumWithSimpleNumber = 100(USD) + 23.560
println(s"sumWithSimpleNumber: $sumWithSimpleNumber")
val multiplicationWithSimpleNumber = 100(USD) * 23
println(s"multiplicationWithSimpleNumber: $multiplicationWithSimpleNumber")
val usd = Currency("USD")
val multiplication = 100(usd) * 23(EUR)
println(s"multiplication: $multiplication")
val divisionWithSimpleNumber = 100(USD) / 23
println(s"divisionWithSimpleNumber: $divisionWithSimpleNumber")
val comparison = 100(USD) > 90(EUR)
println(s"100 USD > 90 EUR? $comparison")
}
}
As you can see the client code just needs two simple imports and an implicit value of type Converter
in order to use the DSL. The operations shown in the previous code are only a few among the available ones.
Have a look at the Money
class for a complete coverage.