2

PSSQ stand for Possibly Stupid Scala Question :)

Getting to know Scala a little bit, and in the obligatory Hello World example (code below) the arguments to the main function is an array of strings.

object HelloWorld
{
    def main(args: Array[String]): Unit = 
    {
        args.map((arg:String) => arg.toUpperCase());
        printf("%s %s!", "Hello", "World");
    }
}

In the example, I'm using the map() function on the array. However, when I check the Scala API documentation, map() isn't listed as one of the functions available for Array. Is there some kind of magic going on, or am I missing something obvious in the API documentation?

0__
  • 66,707
  • 21
  • 171
  • 266
tmbrggmn
  • 8,680
  • 10
  • 35
  • 44
  • 3
    Don't use that style of identation for `{`. Put it on the same line of declaration, whatever else you may do. You may dislike how it looks, but it will save you trouble. – Daniel C. Sobral Apr 12 '11 at 18:51

2 Answers2

3

This is because of one key feature of Scala called implicit conversions. There is plenty of documents about them on the net, for instance see this one: http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-6

The upcoming Scala 2.9 REPL can help you find out which might be involved here:

scala> :implicits -v

... looking for Array we find several ones that go to mutable.ArrayOps. The scaladoc for that one: http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/scala/collection/mutable/ArrayOps.html

This means that since the implicit conversion method refArrayOps is in scope (in the default Predef), whenever you try to call a method on an Array that is not defined for Array but for ArrayOps, scala will insert (implicitly) the conversion, hence you actually have

Predef.refArrayOps(args).map(...)
0__
  • 66,707
  • 21
  • 171
  • 266
1

The simple answer: map is actually a method on the Traversable trait, which is included by Array.

The hard answer: Array doesn't really extend Traversable anymore (iirc), but when Traversable methods are called on an Array instance, there is an implicit conversion that happens in order to allow that to work.

Jonathan Sterling
  • 18,320
  • 12
  • 67
  • 79