Thursday 1 January 2015

String Operations in Scala


1. Scala treats a string as a sequence of characters. A Scala String is a Java String, so you can use all the normal Java string methods.

2. But because Scala offers the magic of implicit conversions, String instances also have access to all the methods of the StringOps class, so you can do many other things with them, such as treating a String instance as a sequence of characters.

scala> "hello".foreach(println)

3.
In Scala, you test object(Value) equality with the == method. This is different than Java, where you use the equals method to compare two objects.


In Scala, the == method defined in the AnyRef class first checks for null values, and then calls the equals method on the first object (i.e., this) to see if the two objects are equal. As a result, you don’t have to check for null values when comparing strings.

scala> val s1: String = null
scala> val s2 = "Hello"
scala> s1 == s2
res3: Boolean = false

4. Imagine that Scala doesn’t even have a null keyword. Any time you feel like using a null, use an Option instead. 

5. Sometimes, the string is too long to write in one line, below example can write a string in multiple lines, but display in one line as result.


val speech = """Four score and
               |seven years ago

               |our fathers""".stripMargin.replaceAll("\n", " ")

6. Adding yield to a for loop essentially places the result from each loop iteration into a temporary holding area. When the loop completes, all of the elements in the holding area are returned as a single collection.


scala> val upper = for (c <- "hello, world") yield c.toUpper

7. Map approach is used to transform one collection into another. The map method treats a String as a sequential collection of Char elements. The map method has an implicit loop, and in that loop, it passes one Char at a time to the algorithm it’s given.


val toLower = (c: Char) => (c.toByte+32).toChar
scala> "HELLO".map(toLower)

No comments:

Post a Comment