What Scala feature allows the plus operator to be

2020-04-02 08:12发布

问题:

I'm still learning Scala, and when I ran across an example in the Koans, I wasn't able to understand why it works:

var foo : Any = "foo"
println(foo + "bar")

Any doesn't have a + method

回答1:

There is an implicit conversion in the scala.Predef object:

implicit def any2stringadd(x: Any): StringAdd

StringAdd defines a + operator/method:

def +(other: String) = String.valueOf(self) + other

Also, since scala.Predef is always in scope, that implicit conversion will always work.



回答2:

It works because of implicit conversions which "fixes" certain type errors for which conversions have been provided. Here is more info on the mechanism of implicit conversions:

http://www.artima.com/pins1ed/implicit-conversions-and-parameters.html#21.2

In fact it uses this very same example x + y to explain how it works. This is from the 1st edition of the book, but the explanation is still valid.



标签: scala