字符串隐式转换列表,例如+ = [英] List of String implicit conversions like +=
问题描述
请考虑以下代码段. + =不是java.lang.String的成员,所以我猜正在进行某种隐式转换.如何找到作用在String上的此类预定义隐式转换的列表?
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
推荐答案
您选择了一个特别糟糕的示例.从某种意义上说,+=
是String
的一部分.请参阅Javadoc上的java.lang.String
注释:
You picked a particularly bad example. +=
is, in a sense, part of String
. See this comment on the Javadoc for java.lang.String
:
Java语言为字符串提供了特殊的支持 并置运算符(
+
),并将其他对象转换为 字符串.
The Java language provides special support for the string concatenation operator (
+
), and for conversion of other objects to strings.
您必须查找 Java语言规范,以查找有关该规范的更多信息(15.18.1 ).但是,同样,Scala不是Java,因此+
也是
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).
到目前为止,我所说的是+
,而不是+=
.但是,Scala具有特殊的语法糖来分配.如6.12.4节所述,除了<=
,>=
,!=
和以=
开头的运算符外,任何以等号结尾的运算符(请参见第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
将重新解释为
x = x + 1
无论x
是否为var
,都将发生这种情况,因此有时可能会看到错误消息"reassignment to val
".
That will happen regardless of whether x
is a var
, so one might occasionally see an error message "reassignment to val
".
因此,如您所见,通过在Scala规范中复制的Java规范中的异常以及一些语法糖,+=
确实是String
的一部分.
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.
这并不意味着java.lang.String
中没有没有可以通过隐式转换与之配合使用的方法.但是,我将其留给其他答案.如果我是你,我将更改问题中的方法以使其正确.此外,+=
在堆栈溢出中不可搜索.
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.
这篇关于字符串隐式转换列表,例如+ =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!