michaelahlers / scala-guide

Helpful recommendations and practical solutions for the working professional.
MIT License
2 stars 0 forks source link

Demonstrate Using `Numeric`; Reinforce Type Classes, Modeling Business Domains #5

Open michaelahlers opened 10 months ago

michaelahlers commented 10 months ago

In place of methods and ad hoc extension methods, remember that type classes solve this problem elegantly and unlock worlds of functionality thanks to this form of ad hoc polymorphism.

Don't do this:

case Money(quantity: Long) { self =>
  def + (other: Money): Money = Money(self.quantity + other.quantity)
}

Or this:

case Money(quantity: Long)

implicit class MoneyOps(private val self: Money) {
  def + (other: Money): Money = Money(self.quantity + other.quantity)
}

Do this:

case Money(quantity: Long)
object Money {
  implicit object numeric extends Numeric[Money] {
    def plus(self: Money, other: Money) = Money(self.quantity + other.quantity)
  }
}

And reap the rewards of an existing ecosystem of functionality (provided, for example, by types like Ordering[A]).

michaelahlers commented 10 months ago

Money is probably a poor example here. It's most likely not a scalar value (there'll be a unit [a currency] associated). And it doesn't always make sense to divide and multiply monetary amounts to obtain the like.