Array的apply方法疑问

val a = Array(1,2,3)
a(1)
这里的a(1)应该是调用class Array的apply方法
我在源码中并没有看到具体的实现在哪里,请问这里获取数据是怎么实现的!

  /** The element at given index.
   *
   *  Indices start at `0`; `xs.apply(0)` is the first element of array `xs`.
   *  Note the indexing syntax `xs(i)` is a shorthand for `xs.apply(i)`.
   *
   *  @param    i   the index
   *  @return       the element at the given index
   *  @throws       ArrayIndexOutOfBoundsException if `i < 0` or `length <= i`
   */
  def apply(i: Int): T = throw new Error()
阅读 3.9k
3 个回答
https://www.scala-lang.org/api/current/scala/Array.html#apply(idx:Int):A
Implicit

This member is added by an implicit conversion from Array[T] to ArrayOps[T] performed by method genericArrayOps in scala.Predef.

Shadowing

This implicitly inherited member is shadowed by one or more members in this class.
To access this member you can use a type ascription:
(array: ArrayOps[T]).apply(idx)
Definition Classes
SeqLike → GenSeqLike
Exceptions thrown
IndexOutOfBoundsException if idx does not satisfy 0 <= idx < length.

这个问题涉及到Scala语言中的隐式转换机制。

val a = Array(1,2,3)
a(1)

第一步:

a.apply(1)

第二步(因为Array里面没有apply方法,所以需要隐式转换):

scala.Predef.genericArrayOps(a).apply(1)

你只要在Idea里面查看ArrayOps的源代码,就可以确认apply的具体实现逻辑在哪儿。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进