Search
  • Arunav Sanyal

Implicit classes in Scala 2.x

Classes in Scala come with a bunch of methods that facilitate some computation.


For instance, lets take the Int class in Scala https://www.scala-lang.org/api/2.12.2/scala/Int.html. It supports basic arithmetic operations like adding, multiplying etc as well as logical operation. However note that it cant support more complex math operations like computing the square root, or computing an exponent.


Now obviously you can use a library like https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html to compute these operations. However, lets say that you would rather want to "extend Int do be able to perform these operations, or create a new operator for power


Well for that you can use implicit classes.

 
 object Math {
    implicit class MathInt(val base:Double) {
     // Add other math operators you would like
     def ** (pow: Int): Int = 
         if (pow==0) 
             1 
         else 
             base*(base**(pow-1))
    }
 }

Now you can import the Math object and then run operations, like

import Math._

2 ** 3 // Returns 9
4 ** 5 // Returns 1024

And that's it. You have a brand new power operator that works over the int type. Note that the import clause above effectively "brings in an implementation" that works over a specific class.


2 views0 comments

Recent Posts

See All

So I love programming in Scala and do so at my daily job. As you may (or may not know) Scala comes with first class support for functional programming. New folks joining our team are often at a loss o