开发者

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

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)="Osc开发者_如何学编程ar"
val x = name.map {  ( s: String ) => s.toUpperCase }
// returns: x: Array[java.lang.String] = Array(OSCAR)


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜