Because String
is a class, it has methods on it that you can use. This is the way classes work in OOP languages.
These examples demonstrate some of the common methods that you’ll use on a String
, with the results of each method shown after the comment:
val a = "hello, world"
a.length // 12
a.capitalize // "Hello, world"
a.toUpperCase // "HELLO, WORLD"
a.indexOf("h") // 0
a.indexOf("e") // 1
a.substring(0, 2) // "he"
a.substring(0, 3) // "hel"
a.substring(1, 3) // "el"
A String
is an immutable data type, meaning that once it’s created, it can never be changed. So when you call any of these methods, you always have to assign the result to a new variable:
val b = a.capitalize // b: "Hello, world"
val c = a.toUpperCase // c: "HELLO, WORLD"
Many more methods
There are actually many more methods available to a String
instance. For instance, when I type a string in the REPL, then add a period, and then press the [Tab]
key, the REPL tells me that there are 248 methods, to be precise:
scala> "yo".
JLine: do you wish to see all 248 possibilities (50 lines)?
But don’t be intimidated by that because you’ll probably only use 10 to 20 methods on a regular basis. After that it’s nice to know that all these other methods are there to help you solve your problems, but the most common 10-20 methods will get you through most days.
In the lessons that follow, you’ll see many of these common methods.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Seq[Char]
It’s worth noting that a Scala String
can be treated as a Seq[Char]
— sequence of characters — whenever you want to work with it this way. For example, you can access the elements in a String
using the usual sequence syntax (specifying the index inside parentheses) and doing that returns the element as a Char
value:
scala> val s = "hello"
val s: String = hello
scala> s(0)
val res0: Char = h
A for
loop is another good example of this:
scala> for c <- s do println(c)
h
e
l
l
o