Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the definition of Array.map in Scala is "throw new Error()"

Tags:

scala

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)
like image 573
OscarRyz Avatar asked May 21 '10 19:05

OscarRyz


2 Answers

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

like image 44
pdbartlett Avatar answered Oct 11 '22 14:10

pdbartlett


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.

like image 109
retronym Avatar answered Oct 11 '22 14:10

retronym