Upio
Upio

Reputation: 1374

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?

Upvotes: 6

Views: 270

Answers (1)

Ajay Padala
Ajay Padala

Reputation: 2401

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

Upvotes: 7

Related Questions