At first glance, a Scala String appears to be just a Java String. Indeed, a Scala String is a Java String, so you can use all the normal java Strings methods. Calling getName method on String class results a java.lang.String.
|Calling getName method of String class in REPL|
You can create a String variable, albeit in the Scala way.
You can get the length of a Stringval s = "Hello, World" // Immutable String s represents "Hello, World"
s.length // 12
You can concatenate Strings
val s = "Hello" + "World"
Magic Of Implicit Conversions:
The above all are familiar operations. In Scala, Strings instances also have access to all the methods of the StringOps class. So you can do many other things with them , for example, treating String instance as a sequence of characters. As a result, you can iterate over every character in the String using foreach method.
scala > "Hello".foreach(println)output : Hello
You can treat a String as a sequence of characters in a for loop :
scala > for (c <- "hello") println(c)output : hello
You can also treat it as a sequence of bytes:
scala> "hello".getBytes.foreach(println)output : 104101108108111
Because there are many methods available on sequential collections, you can also use other functional methods like filter :
Even though the String class is declared as final in Java, you've seen that Scala some how adds new functionality to it. This happens through the power of implicit conversions. Because of this, scala string has both String and collection features. see the below examplescala > val result = "hello world".filter(_ != 'l')output : result: String = heo word
scala > "scala".drop(2).take(2).capitalizeres0 : String = Al
Here drop is a collection method that drops (discards) the number of elements that are specified from the beginning of the collection & keeps the remaining elements.
The take(2) method retains the first two elements from the collection it's given and discards the rest.scala > "scala".drop(2)res1 : String = ala
finally, you treat the output from the take(2) method like a String and once again call the capitalize method to get what you want :scala > "scala".drop(2).take(2)res2 : String = al
scala > "scala".drop(2).take(2).capitalizeres3: String = Al