scala-4

Scala:
-----------------------------
The s interpolator
It allows the use of variable directly in processing a string, when you prepend ‘s’ to it.
val name = "John"
println(s"Hello $name") //output: Hello John
String interpolation can also process arbitrary expressions.
println(s"2 + 3 = ${2 + 3}") //output: 2 + 3 = 5
The f interpolator
It allows creating a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc.
val height = 1.7d
val name = "John"
println(f"$name%s is $height%2.2f meters tall") //John is 1.70 meters tall
The raw interpolator
It is similar to s interpolator except that it performs no escaping of literals within a string.
Output with s option:
println(s"Result = \n a \n b")
Result =
 a
 b
Outout with raw option:
println(raw"Result = \n a \n b")
Result = \n a \n b

Example 1:
object Hello {
   def main(args: Array[String]) {
      // Local variable declaration:
      var a = 5;
      // while loop execution
      while( a < 10 ){
         a = a + 1;
         println( "Value of a: " + a );
      }
   }
}
Example 2:
object Hello {
   def main(args: Array[String]) {
      // Local variable declaration:
      var a = 5;
      // do loop execution
      do {
         a = a + 1;
         println( "Value of a: " + a );          }
      while( a < 10 )
   }
}
Example 3:
object Hello {
   def main(args: Array[String]) {
      var a = 0;
      // for loop execution with a range
      println("Loop 1 - simple loop")
      for( a <- 1 to 5){
         println( "Value of a: " + a );
      }
      println("Loop 2 - loop with custom incremental value")
      for( a <- 1 to 10 by 2){
         println( "Value of a: " + a );
      }
      println("Loop 3 - loop in reverse, decreasing order")
      for( a <- 5 to 1 by -1){
         println( "Value of a: " + a );
      }
      println("Loop 4 - loop using until, one iteration less than simple loop")
      for( a <- 5 until 1 by -1){
         println( "Value of a: " + a );
      }
      println("Loop 5 - loop over collections")
      val myList = List(1,2,3,4,5);
      for( a <- myList ){
         println( "Value of a: " + a );
      }
      println("Loop 6 - loop over multiples ranges, loop within loop")
      for( a <- 1 to 5; b <- 1 to 3){
         println( "Value of a: " + a );
         println( "Value of b: " + b );
      }
   }
}

Comments