Like implicit variables, implicit methods offer a great deal of flexibility in Scala. They help us in wrapping up objects. However, it can make us very tired, if overused. Here’s an example of using implicit methods.
Let me implement one of my favorite Groovy examples from the book, Programming Groovy (Venkat Subramaniam) using implicit methods in Scala.
def main(args:Array[String]):Unit = { println(5 daysFromNow) }
5 daysFromNow is self-explanatory. But compiler will give you an error, saying daysFromNow is not a member of Int. So let’s get into action. We need to tell the compiler that Int will be implicitly converted to an Object that has daysFromNow behavior. Let’s do that.
implicit def hereWeGo(x:Int) = { new CalendarUtil(5) }
The hereWeGo() method is defined as implicit. It takes in an integer and returns an instance of CalendarUtil as shown above. So here is the class CalendarUtil.
class CalendarUtil(count:Int){ def daysFromNow() = { import java.util.{Date,Calendar} val cldr = Calendar.getInstance cldr.setTime(new Date()) cldr.add(Calendar.DATE,count) cldr.getTime() } }
And that’s the power of implicit methods.