Scala Journals — The mystery of Implicits debunked

Annette
Level Up Coding
Published in
7 min readSep 7, 2020

--

Source: Unsplash

Today I will cover quite an interesting topic — implicits. They are almost as interesting as they are infamous for adding to codebase complexity and debugging hell stories (Spoiler alert: as you will find out soon — only if they are used incorrectly).

So let’s try and find out what are they, why are they needed and most importantly — when should we use them in real life? As it turns out again… once you grasp the basics they are not as terrifying as they are made to be.

What are implicits

As time goes by and you get used to working with Scala you eventually come across a similar compiler error message:

error: could not find implicit value for parameter reads: JsonReads[Order]

I like checking the meaning of programming jargon in the English dictionary to really try and understand why something is called the way it is. So let’s double check what implicit means in the language of humans. Collins dictionary says:

“Something that is implicit is expressed in an indirect way.”

So we can adapt it to match the Scala realm:

Something being implicit means it is passed and used in an indirect way, “behind the scenes”.

Here is an example of an implicit value usage. (Disclaimer: this is a horrible practise but it illustrates the idea behind implicits in just a few lines of code. Please don’t ever use implicits for something like this). Pay close attention to package location of the code snippets:

// inside com.taxwebsite.StaticValues
...
implicit val vat: Double = 0.19
...
// inside com.taxwebsite.TaxCalulator
...
def getPriceWithTax(amount: Int)(implicit vat: Double) = amount + amount * vat
...
// inside com.taxwebsite.PriceService
import com.taxwebsite.StaticValues.vat <- important chunk here!
...
def getFinalPrice(amount: Int) = getPriceWithTax(amount)
...

In the above code example we have an implicit value vat that gets imported into the scope of PriceService. Because the vat value is marked as implicit it’s then not necessary to…

--

--