Contenido del Curso
Introduction to Scala
Introduction to Scala
What is a String?
Despite not yet learning what strings are, we have already dealt with them in the previous chapters.
Let's now discuss what a string is:
In other words, strings are essentially used to store and manipulate text.
Creating a String
Basically, creating a string in Scala means simply creating a variable of the String
class:
Main
// Without type inference var greeting: String = "Hello, Scala!" // With type inference var greeting = "Hello, Scala!"
Once again, we can safely omit specifying the String
data type explicitly and rely on type inference. This is especially common with strings in Scala since only a String
is typically represented by enclosing text within double quotes ""
.
Let's illustrate this with an example:
Main
object Main { def main(args: Array[String]): Unit = { var greeting = "Hello" greeting += "World" println(greeting) } }
In this code, greeting
initially points to the String
object "Hello"
. When "World"
is concatenated, a new String
object "Hello World"
is created and greeting
is updated to refer to this new object. The original "Hello"
string remains unmodified in computer memory.
Concatenating Strings
We have just used string concatenation in the example above, but what it really is?
There are several ways to perform it, but the most commonly used approaches are the following:
- using the
+
operator; - using the
concat()
method of theString
.
Here is an example of using both of them:
Main
object Main { def main(args: Array[String]): Unit = { val firstName = "Mike" val lastname = "Tyson" // First approach val fullName1 = firstName + " " + lastname println(fullName1) // Second approach val fullName2 = firstName.concat(" ").concat(lastname) println(fullName2) println(fullName1 == fullName2) // Verifies that they are equal } }
As you can see, both approaches yield the same result. In fact, using +
is just a shorthand for the concat()
method.
Array of Strings
Like with all data types, classes and even data structures, we can also create an array of strings in Scala. Here's an example:
Main
object Main { def main(args: Array[String]): Unit = { val stringArray = Array("hello", "darkness", "my old", "friend") for (item <- stringArray) { print(item + " ") // String concatenation } } }
As you can see, everything is simple here. The only difference from the previous array example is that the data type of array elements is String
.
¡Gracias por tus comentarios!