# Simple Scala money library

for some fun, I decided to start working on something that let me work with Money calculations. I realise there are libraries out there like Joda Money, but I'm doing this mainly for fun.

I was hoping to get a review on the way I've started to construct the library.

GitHub

private def calculate(that: Money)(f: (BigDecimal, BigDecimal) => BigDecimal): Either[String, Money] = (this.currency, that.currency) match {
case (c, c1) if c == c1 => new Right(this.copy(this.currency, f(this.amount, that.amount)))
case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}

private def compare(that: Money)(f: (BigDecimal, BigDecimal) => Boolean): Either[String, Boolean] = (this.currency, that.currency) match {
case (c, c1) if c == c1 => new Right(this.amount > that.amount)
case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}


These two methods are incredibly similar except for the return type. Could someone suggest a way to improve this?

First thoughts:

• If an operation can fail, it is generally good practise to make this explicit in the API by returning a Try instead of an Either.
• The duplicate code seems to stem from the fact that Money operations are only valid on Currencies of the same type. Scala gives you the power to have this check at compile time.

Example Code:

object Money {
sealed trait Currency
case object GBP extends Currency
}
case class Money[T <: Money.Currency](amount: BigDecimal) {
private def calculate(that: Money[T])(f: (BigDecimal, BigDecimal) => BigDecimal): Money[T] = {
copy(amount = f(this.amount, that.amount))
}
private def compare(that: Money[T])(f: (BigDecimal, BigDecimal) => Boolean): Boolean = {
this.amount > that.amount
}
}

• Thank you. Are there any examples in libraries or anything that prefer returning try over either?
– user109692
Commented Oct 27, 2016 at 12:05
• This blog post gives a good overview of exception handling with Scala: danielwestheide.com/blog/2012/12/26/… Commented Nov 10, 2016 at 17:25