Implicit in Scala

One of the magic behavior’s in scala is implicit. This can be used in so many situations. The most common use case is which helps to avoid helper / utility classes.

Eg:- “Hello”.printChar Not StringHelp.printChar(“Hello")

It’s important we need to define it within the scope where these method definitions are allowed. Therefore it can be inside a class or object.

implicit class StringHelp(s: String) {
  def printChar = s.map(c => println(c))
}

"Hello".printChar

##Implicit argument

Implicit can be used as arguments too. But it’s bit weird though but it’s really handy.

def printImplicitly (implicit arg : String) = println(arg)
printImplicitly("Hello World - 1")

implicit val hello = "Hello World - 2"
printImplicitly

So we can pass the implicit argument or additionally we can allow the compiler look for a value in the enclosing scope that has been marked as implicit. If the compiler didn’t find a implicit variable it will throw an error.

##Implicit with in an object

object HelperModule {
  implicit class StringHelp(s: String) {
    def printChar = s.map(c => println(c))
  }
}

object Main extend App{
    import HelperModule._
    "Scala Awesome".printChar
}

Once we properly place the implicit classes inside object/packages it can be imported to the specific places. This approach will help to use it appropriately.

A major benefit of these approaches is that you don’t have to extend classes to incorporate new features. And also the api your using in your code will be nicely structured with native scala api.

I hope, this should provide enough to get you started with implicit.

Blog Series