I have the following two Scala files:
object ImplicitsHome {
implicit class StringWrapper(val str: String) extends ImplicitsHome with Serializable
}
trait ImplicitsHome {
def str: String
def embelishString: String = {
str.concat("fancy")
}
}
and:
import ImplicitsHome._
class User {
def buildSuperString(str: String): String = {
str.embelishString
}
}
object User {
def main(args: Array[String]): Unit = {
val usr = new User()
val fancy = usr.buildSuperString("hi")
println(fancy)
}
}
What I am wondering is that, if I have to call the embelishString function more than once, will I be creating multiple instances of the implicit StringWrapper class?
I'm concerned about this because when the implicit is used, it passes a String (str) in - is it 'state' that I have to be careful about sharing across different invocations of the embelishString function?
Every time you call
embelishString- new instance ofStringWrappercreated. It's pretty much cheap if you don't have a heavy constructor/state for implicit class, which usually you don't (empty constructor and pointer to someString-object in your case). So there is no reason to concern. More than that -Stringis immutable (so asStringWrapper) - this means you shouldn't worry about shared state anyway.Example: