Consider the following snippet. += is not a member of java.lang.String, so I guess there is some sort of Implicit conversion going on. How do I find a list of such predefined implicit conversions acting on String?
scala> var x = "asdf"
x: java.lang.String = asdf
scala> x += x
scala> x
res2: java.lang.String = asdfasdf
You picked a particularly bad example. +=
is, in a sense, part of String
. See this comment on the Javadoc for java.lang.String
:
The Java language provides special support for the string concatenation operator (
+
), and for conversion of other objects to strings.
You'll have to look up Java language specification to find more information about it (15.18.1). But, then again, Scala is not Java, so +
is also part of the Scala language specification (12.3.1).
So far I have spoken of +
, not +=
. However, Scala has a special syntactic sugar for assignment. As described in section 6.12.4, except for <=
, >=
, !=
and operators starting with an =
, any operator symbol (see "operator characters" in chapter 1) that ends in an equal sign will be reinterpreted if it does not exist as a method. Specifically,
x += 1
will be reinterpreted as
x = x + 1
That will happen regardless of whether x
is a var
, so one might occasionally see an error message "reassignment to val
".
So, as you can see, +=
is really part of String
, through an exception in Java specification that was replicated in Scala specification, plus a bit of syntactic sugar.
Which doesn't mean there aren't methods not in java.lang.String
that can be used with it through implicit conversions. I'll leave that to the other answers, however. If I were you, I'd change the method in the question, to make it correct. Besides, +=
is unsearchable in Stack Overflow.
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