Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Scala feature allows the plus operator to be used on Any?

Tags:

scala

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

like image 278
Bryan Young Avatar asked Sep 19 '11 01:09

Bryan Young


2 Answers

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.

like image 140
Dylan Avatar answered Nov 07 '22 06:11

Dylan


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.

like image 20
huynhjl Avatar answered Nov 07 '22 07:11

huynhjl