Scala and implicit class instantiation -
i have following 2 scala files:
object implicitshome { implicit class stringwrapper(val str: string) extends implicitshome 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 wondering that, if have call embelishstring
function more once, creating multiple instances of implicit stringwrapper
class?
i'm concerned because when implicit used, passes string (str
) in - 'state' have careful sharing across different invocations of embelishstring
function?
every time call embelishstring
- new instance of stringwrapper
created. it's pretty cheap if don't have heavy constructor/state implicit class, don't (empty constructor , pointer string
-object in case). there no reason concern. more - string
immutable (so stringwrapper
) - means shouldn't worry shared state anyway.
example:
scala> implicit class aaa(a: string) {println(a); def aa = 5} //added println constructor defined class aaa scala> "aaa".aa; "aaa".aa; "bbb".aa aaa //first instantiation (for "aaa".aa) aaa //first instantiation (for "aaa".aa) bbb //third instantiation (for "bbb".aa) res4: int = 5
Comments
Post a Comment