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

后端 未结 2 479
逝去的感伤
逝去的感伤 2021-01-02 07:41

The source code of map for Array is:

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

But the following works:

2条回答
  •  执念已碎
    2021-01-02 08:32

    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.

提交回复
热议问题