Making ordinary classes Rich! (Scala)

Lalit Vatsal
Oct 7 · 2 min read

Let me break it to you, this post has nothing to do with charity! Now, let’s start with a question:

How do we enrich something?

By making it abundant, rich in features and resourceful!

In simple OOP terms, we add additional feature methods to the class!!

Let’s try to enrich a Person class, starting with the basic class:

Now, to make a person speak French, we have to add another method to our Person class:

This is perfectly fine! Just add the additional feature to the existing class and make it rich.

But… there are cases when we cannot add features/methods to classes, like, library classes (java.util.Date, String, etc).

To add features to such classes we have to make “wrapper classes”. Suppose we want to add the “spell the digits” feature in the standard libraries Int class, we would have to make a wrapper class over Int.

Problem with this wrapper class approach is, if the desired class’ objects are used in a lot of places, then refactoring the class objects to our Rich-Wrapper class objects becomes a real pain!

Solution: Implicit classes and extension methods

We will now make slight changes to our wrapper class:

  1. Add an implicit keyword in front of the class.
  2. Put the implicit class in a container object, which has a reason but also is generally a good practice. This way, we can import the “rich” feature at will!
  3. Import contents of the container object.
  4. Use the method on simple objects directly!

This pattern of creating an implicit class to enhance a library’s features has a funny name

“Pimp My Library Pattern”

The example we shown above was a very basic example of Implicit class and its extension methods. The application of Implicit classes reach far beyond this!

One such example, is creating a generic method time profiler:

Then, what are your waiting for? Since, now you’ve learned to “pimp” any library, go make the mundane library objects rich with features you like!

fin.

Lalit Vatsal

Written by

Algorithms, FP and distributed systems Enthusiast. #Java #Scala #Python. Software Engineer @WalmartLabs

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade