Apply in scala Array


#1

If I do something like this for an array:
myArray(i)
It gets compiled as:
myArray.apply(i)
So there is an apply method in scala Array class.

Also, when I do:
val myArr = Array(“Hello”,“World”)
It gets transformed into:
val myArr = Array.apply(“Hello”,“World”)

So, are these two overloaded versions of apply?


#2

The second case Apply("Hello", "World") is the apply method on the companion object of the class Array.


#3

So we have an apply method both in Array class as well as Array companion object. And they differ in their signature.


#4

Correct. That’s just routine overloading, and has nothing to do with apply() per se – you are always allowed to overload a method name with multiple implementations that have different signatures. (Not everyone thinks this is a wise thing to do, but it’s totally legal.)


#5

This is not a case of overloading. Overloading is when you have two methods in the same scope with different signatures. That isn’t what is going on here. These two apply methods are in completely different scopes. We can illustrate that with the following little example.

class Overload {
  def foo(): Unit = println("class foo")
}

object Overload {
  def foo(): Unit = println("object foo")
}

Note that both definitions of foo have the same signature. That wouldn’t be allowed for overloading. It is legal here because this isn’t overloading. One version must be called on an instance of the class while the other must be called on the companion object.