Reputation: 5659
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?
Upvotes: 0
Views: 706
Reputation: 22374
Every time you call embelishString
- new instance of StringWrapper
created. 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 some String
-object in your case). So there is no reason to concern. More than that - String
is immutable (so as StringWrapper
) - this means you shouldn't worry about shared state anyway.
Example:
scala> implicit class Aaa(a: String) {println(a); def aa = 5} //added println to constructor
defined class Aaa
scala> "aaa".aa; "aaa".aa; "bbb".aa
aaa //first instantiation (for "aaa".aa)
aaa //first instantiation (for another "aaa".aa)
bbb //third instantiation (for "bbb".aa)
res4: Int = 5
Upvotes: 3