为什么Scala中Array.map的定义是“throw new Error()"? [英] Why does the definition of Array.map in Scala is "throw new Error()"

查看:43
本文介绍了为什么Scala中Array.map的定义是“throw new Error()"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组是:

The source code of map for Array is:

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

但以下有效:

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)

推荐答案

一般来说,当你在一个库类的源代码中看到 throw new Error() 时,它代表了编译器通过桥接到平台的工具(请记住这可以是 Java 或 .NET)来干预和实施该方法.

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).

Array SID 解释了过去在 Scala 2.7.x 中如何处理数组,以及它们在 2.8 中的变化.如果您调用了 map,编译器曾经神奇地将对象转换为 BoxedArray.

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.

在 2.8 中,将 Arrays 集成到 Scala 集合框架中主要是通过使用正常的语言功能来处理的——从 Array[T]WrappedArray[T]ArraySeq[T],取决于上下文,以及类型 Manifest[T] 的隐式参数,以支持创建泛型类型 T.数组 索引长度update 仍然显示为throw new Error().Array#map 不再存在,您可以在 WrappedArrayArraySeq 上找到它作为常规方法.

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.

更新

如果你有兴趣知道这个编译器魔法的定义,看看 Cleanup.scala.

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

这篇关于为什么Scala中Array.map的定义是“throw new Error()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆