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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With