Implicit Classes in Scala- Their Uses and How to create them?

Reading Time: 2 minutes

What is an implicit class

An implicit class in Scala is a normal scala class but with an implicit keyword before it. They allow the user to add methods to exiting classes and use them as if they belong to those classes.

The feature is available since Scala 2.10.

This is how we declare an implicit class in Scala:

implicit class <class_name>(args...)

In short, they allow us to add behaviors to pre-defined types in Scala without meddling with their source code.

Example

Let’s understand the concept through an example.

In this example, we are creating a method to capitalize the first letter of every word.

(I know there are better ways to do this but for the purpose of this blog we will be not be using them)

object ImplicitPractice extends App {

  implicit class StringUtils(str: String) {
    
    def capitalizeEachWord(): String = str.split(" ").map(word => word.capitalize).mkString(" ")
  }
......
}

Here, we create an implicit class name StringUtils. Next, we add a method capitalizeEachWord() which will perform our logic.

Now, to make use of this method we add the following lines.

  val inputString = "my name is prakhar"
  println(inputString.capitalizeEachWord())

As we can see we are able to access the capitalizeEachWord() method as if it belongs to the String class of the Scala standard library.

Running the above lines of code produces the following output:

Implicit class example in Scala

Working of implicit classes

When we create an implicit class the compiler generates some code internally. This allows us to seamlessly use it the way we are in the above example.

// Automatically generated by the comiler
implicit def StringUtils(str: String) = new StringUtils(str)

And when we call the capitalizeEachWord() method this is how the actual call is made under the hood.

  println(StringUtils(inputString).capitalizeEachWord())

Restrictions

Implicit classes cannot and should not be used in every situation like:

  1. We can only define them inside a trait, class, object or package object. They cannot act as top-level objects.
  2. Must contain only one explicit paramter in their constructor
  3. Cannot be a case class.

Conclusion

So in conclusion we can say that implicit classes are a remarkable addition to Scala that allows developers to extend the functionality of existing types.

However, we must be mindful of the restrictions for using them as well.

It saves us from writing a lot of boilerplate code by just adding the keyword implicit before the class.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading