Chapter 2. Strings

As programmers, we deal with strings all the time—names, addresses, phone numbers, and the like. Scala strings are great because they have all the features of Java strings, and more. In this chapter you’ll see some of the shared features in the recipes on string formatting and using regex patterns, while the other recipes demonstrate features that are unique to Scala.

Because of the syntax of the Scala language, one major difference with Java is in how Scala strings are declared. All Scala variables are declared as a val or var, so a string variable is typically created like this:

val s = "Hello, world"

That expression is equivalent to this Java code:

final String s = "Hello, world"

In Scala the general rule of thumb is to always declare a variable as a val, unless there’s a good reason to use a var. (Pure functional programming takes this further, and strictly forbids the use of var fields.)

You can also explicitly declare a String type:

val s: String = "Hello, world"   // don’t do this
       ------

However, that isn’t recommended because it only makes your code unnecessarily verbose. Because Scala’s type inference is very powerful, the implicit syntax shown in the first example is sufficient, and preferred. In fact, as a practical matter, the only time I declare a type explicitly when creating a variable is when I call a method and it’s not clear from the method name what its return type is:

val s: String = someObject.someMethod(42)

Scala String Features

Additional ...

Get Scala Cookbook, 2nd Edition 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.