Saturday, 28 June 2014

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.

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 : H

e

l

l

o

You can treat a String as a sequence of characters in a for loop :

scala > for (c <- "hello") println(c)

output : h

e

l

l

o

You can also treat it as a sequence of bytes:

scala> "hello".getBytes.foreach(println)

output : 104

101

108

108

111

Because there are many methods available on sequential collections, you can also use other functional methods like filter :

scala > val result = "hello world".filter(_ != 'l')

output : result: String = heo word

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 example

scala > "scala".drop(2).take(2).capitalize

res0 : 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.

scala > "scala".drop(2)

res1 : String = ala

The take(2) method retains the first two elements from the collection it's given and discards the rest.

scala > "scala".drop(2).take(2)

res2 : String = al

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 :