Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
Upio Avatar asked Apr 10 '15 05:04

Upio


1 Answers

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

like image 80
Ajay Padala Avatar answered Nov 13 '22 17:11

Ajay Padala