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:
vals="Hello, world"
That expression is equivalent to this Java code:
finalStrings="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:
vals: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:
vals:String=someObject.someMethod(42)
Scala String Features
Additional ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access