views:

130

answers:

2

The source code of map for Array is:

override def map[B](f: A => B): Array[B] = throw new Error()

But the following works:

val name : Array[String]= new Array(1)
name(0)="Oscar"
val x = name.map {  ( s: String ) => s.toUpperCase }
// returns: x: Array[java.lang.String] = Array(OSCAR)
+3  A: 

Looks like it's just dummy code, as Scala arrays are really Java ones.

pdbartlett
similar to "native" ? In java, I mean, like... *Hey, don't worry, I know what to do underneath?*
OscarRyz
That'd be my guess, though I don't know for sure.
pdbartlett
+9  A: 

Generally, when you see throw new Error() in the source code of a library class, it represents a point where the compiler is intervening and implementing the method by bridging to a facility of the platform (remember this could be Java or .NET).

The Array SID explains how arrays used to be treated in Scala 2.7.x, and how they have changed in 2.8. The compiler used to magically convert the object to a BoxedArray if you called map.

In 2.8, integration of Arrays into the Scala collections framework is largely handled with use of normal langauges features -- implicit conversions from Array[T] to WrappedArray[T] or ArraySeq[T], depending on the context, and implicit parameters of type Manifest[T] to support creation of arrays of a generic type T. Array indexing, length and update still appear as throw new Error(). Array#map no longer exists, instead you find this on WrappedArray and ArraySeq as a regular method.

UPDATE

If you're interested to know this compiler magic is defined, take a look at Scala 2.8 incarnation of Cleanup.scala.

retronym