Scala and implicit class instantiation

689 views Asked by At

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?

1

There are 1 answers

0
dk14 On

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