Implicit class is used to add a new behaviour to an existing object without modifying that object. These newly added methods are also called as extension methods.
Using Implicit Class to extend functionality of an object can be very helpful when we do not have access to modify the source object.
An implicit class must be defined in one of these places:
- A class
- An object
- A package object
In the below example we will add the “reverseString” method to String.
package com.scala.test
object Implicit {
implicit class StringImplicit(val s: String) {
def reverseString: String =
(for (i <- s.length – 1 to 0 by -1) yield s(i)).mkString
}
}
You can then use the reverseString method somewhere else in your code, after adding the proper import statement:
package com.scala.test
import com.scala.test.Implicit._
object Main extends App {
println(“GYAN”.reverseString)
}
Output:
NAYG