Search code examples
scalaimplicits

Does the scala compiler do anything to optimize implicit classes?


Say we have an implicit class like:

implicit class RichString(str: String) {
  def sayHello(): String = s"Hello, ${str}!"
}

We can use the method sayHello as if it is defined on the String class

"World".sayHello

Does the scala compiler optimize this to something like a static call to avoid the overhead of constructing a RichString object?


Solution

  • Scala compiler optimises the method call only if you specify the class extends AnyVal. These are called value classes.

    Example from docs, link given below:

    class RichInt(val self: Int) extends AnyVal {
      def toHexString: String = java.lang.Integer.toHexString(self)
    }
    

    http://docs.scala-lang.org/overviews/core/value-classes.html