Using scala implicits to make my code more readable.

Scala implicits can be very frustrating to new users of the language, they were for me.

Their operation seems magical because the compiler chooses when and where to apply them.

A simple use case for implicits is providing type conversions that would otherwise cause a lot of boilerplate code clutter.

Here’s an example adapted from some tests I wrote to check payment calculations for an e-commerce web site.

Payments are represented by a case class like this:

case class Payment(date: DateTime, amount: BigDecimal, note: Option[String])

Here’s how I created a testPayment to compare with my calculations:

val date = ISODateTimeFormat.date.parseDateTime("2014-04-01")
val testPayment = Payment(date, BigDecimal(100.00), Some("comment"))

There’s a lot of boilerplate to get the right types.

I cleaned things up a bit by introducing some implicits in the body of my test:

  
implicit def String2DateTime(value: String): DateTime = ISODateTimeFormat.date.parseDateTime(value)
implicit def String2OptionString(value: String): Option[String] = Some(value)
implicit def Double2BigDecimal(value: Double): BigDecimal = BigDecimal(value)

Once these implicits were in scope my testPayment creation became much easier to read:

val testPayment = Payment("2014-04-01", 100.00, "comment")

Comments are closed.