Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

1.6 The apply Method

In Scala, it is common to use a syntax that looks like a function call. For example, if s is a string, then s(i) is the ith character of the string. (In C++, you would write s[i]; in Java, s.charAt(i).) Try it out in the REPL:

"Hello"(4) // Yields 'o'

You can think of this as an overloaded form of the () operator. It is implemented as a method with the name apply. For example, in the documentation of the StringOps class, you will find a method

def apply(n: Int): Char

That is, "Hello"(4) is a shortcut for

"Hello".apply(4)

When you look at the documentation for the BigInt companion object, you will see apply methods that let you convert strings or numbers to BigInt objects. For example, the call

BigInt("1234567890")

is a shortcut for

BigInt.apply("1234567890")

It yields a new BigInt object, without having to use new. For example:

BigInt("1234567890") * BigInt("112358111321")

Using the apply method of a companion object is a common Scala idiom for constructing objects. For example, Array(1, 4, 9, 16) returns an array, thanks to the apply method of the Array companion object.

  • + Share This
  • 🔖 Save To Your Account