I guess my recent love for scala
is quite evident lately. I began to fall in love with the conciseness and expressive nature of scala
. But more than that, there is one thing that I am currently infatuated with; implicits
– The magic keyword in scala
.
Scala
uses implicit's
heavily to improve the conciseness of many design patterns that are native to functional programming and hence plays a key role in the core design of the language and many libraries in the community.
Let’s get started on how to put implicits
into action and create an extension method
to a class using implicit
‘s.
So, what is this extension method in first place?
Extension methods are like extending a feature to a class that is otherwise in-extensible. Example of an extension method would be able to extend the functionality of Int
class by creating a method that takes in a single digit as a number and returns the digit as a String
. Something similar to the snippet shown below.
1.digitToWord() // This is an extension method on Int class
Clearly, this is not possible in statically typed language as the language would not allow you to add methods to the standard library and would fail to compile.
But scala
has this magic language feature called implicit
specially for performing a trick like this. Let us see how that is done.
implicit class ExtendedInt(val num: Int) {
def digitToWord: String = {
num match {
case 1 => "One"
case 2 => "Two"
case 3 => "Three"
case 4 => "Four"
case 5 => "Five"
case 6 => "Six"
case 7 => "Seven"
case 8 => "Eight"
case 9 => "Nine"
case 0 => "Zero"
case _ => "Not a valid single digit"
}
}
}
Scala
allows you to create an implicit
class which has a method that returns a String
. When we define this in the scope, scala
compiler keeps track of this transformation from Int
to String
in the context and tries to use it whenever appropriate.
So, when you say,
1.digitToWord() // Implicit magic aka extension method call
Scala
compiler will automatically check to see if its able to find one unique implicit
that can take in an Int
, construct an ExtendedInt
and call digitToWord()
. Since we already defined our implicit class Extendednt
to take an Int
to create an instance of ExtendedInt
, compiler silently performs the following transformation for you.
new ExtendedInt(1).digitToWord() // After the implicit magic worn out
Cool isn’t it? Implicit is a complicated feature and would sound like something which makes the code very difficult to debug. Yes, that is true! Implicits are a very powerful feature indeed and often face a lot of criticisms. One has to use implicits
with a word of caution and careful enough to stay responsible because, as Spiderman says,
“With great power comes great responsibility!”
Also yeah, Happy new year!