\$\begingroup\$
\$\endgroup\$
0
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.
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?
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
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
}
}
answered Jun 30, 2016 at 7:31
-
\$\begingroup\$ Thank you. Are there any examples in libraries or anything that prefer returning try over either? \$\endgroup\$user109692– user1096922016年10月27日 12:05:45 +00:00Commented Oct 27, 2016 at 12:05
-
\$\begingroup\$ This blog post gives a good overview of exception handling with Scala: danielwestheide.com/blog/2012/12/26/… \$\endgroup\$Steve Robinson– Steve Robinson2016年11月10日 17:25:13 +00:00Commented Nov 10, 2016 at 17:25
lang-scala