How to access a character in a Scala String (or, an element in a sequence)

When coming to Scala from Java, the syntax for accessing a character at a position in a Scala String is an interesting thing. You could use the Java charAt method:

scala> "hello".charAt(0)
res0: Char = h

However, the preferred (proper) approach to access a character in a String is to use Scala’s Array notation:

scala> "hello"(0)
res1: Char = h

scala> "hello"(1)
res2: Char = e

Discussion

When looping over the characters in a string you’ll normally use the map or foreach methods, but if for some reason those approaches won’t work for your situation, you can treat a String as an Array, and access each character with the array notation shown.

The Scala Array notation is different than Java because in Scala it’s really a method call, with some nice syntactic sugar added. You write your code like this, which is convenient and easy to read:

scala> "hello"(0)
res0: Char = h

scala> "hello"(1)
res1: Char = e

But behind the scenes, Scala converts your code into this:

scala> "hello".apply(1)
res2: Char = e

This little bit of syntactic sugar is explained in detail in Recipe 6.8 of the Scala Cookbook, “Creating Object Instances Without Using the new Keyword.”