You could use the Java charAt
method:
scala> "hello".charAt(0)
res0: Char = h
However, the preferred approach is to use Scala’s Array
notation:
scala>"hello"(0)
res1: Char = h scala>"hello"(1)
res2: Char = e
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"(1)
res0: Char = e
But behind the scenes, Scala converts your code into this:
scala> "hello".apply(1)
res1: Char = e
This little bit of syntactic sugar is explained in detail in Recipe 6.8.
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.