Scala Quick Notes :: Part - 1


Bhaskar S 01/09/2015


Overview

Scala is a modern general purpose hybrid programming language with the following characteristics:

Setup

Download and install the following software:

Hands-on With Scala - I

Best way to learn any language is to get our hands dirty. So without much further ado lets get started.

The following is the Scala program named Sample01.scala:

Sample01.scala
/*
 *
 * Name  : Sample01
 * 
 * Author: Bhaskar S
 * 
 * Date  : 01/09/2015
 *  
 */

package com.polarsparc.scala

import scala.util._

object Sample01 {
  def main(args: Array[String]) = {
    var a: Int = 100
    println("<1> a = " + a.toString())
    println("<2> a = ".+(a))
    
    var b = 0
    for (i <- 1 to 5) {
      b += i
    }
    println("<1> b = " + b)
    
    b = 0
    for (i <- 1.to(5)) {
      b += i
    }
    println("<2> b = " + b)
    
    val c = 5
    for (i <- 1 until c) {
      println("Hello Scala !!! <" + i + ">")
    }
    
    for {i <- 1 to 3
         j <- 1 to 3} {
      println("i = " + i + ", j = " + j)
    }
         
    for {i <- 1 to 10
      if i %2 == 0
      } {
      println("Cool Scala !!! <" + i + ">")
    }
    
    val d = if (c > 0) 5 else -5
    println("d = " + d)
    
    val e = { val x = 3; val y = 5; ((x*x) + (y*y)) }
    println("e = " + e)
    
    val random: Random = new Random
    
    val r1 = 75
    val r2 = 50
    val abc = random.nextInt(100)
    if (abc > r1) {
      println(abc + " is greater than " + r1)
    } else if (abc > r2) {
      println(abc + " is greater than " + r2)
    } else {
      println(abc + " is NOT greater than " + r2 + " or " + r1)
    }
  }
}

NOTE :: Scala program files have the extension ".scala"

Executing the program Sample01.scala results in the output:

Output (Sample01.scala)

<1> a = 100
<2> a = 100
<1> b = 15
<2> b = 15
Hello Scala !!! <1>
Hello Scala !!! <2>
Hello Scala !!! <3>
Hello Scala !!! <4>
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
Cool Scala !!! <2>
Cool Scala !!! <4>
Cool Scala !!! <6>
Cool Scala !!! <8>
Cool Scala !!! <10>
d = 5
e = 34
68 is greater than 50

The following section explains some of the aspects of the Scala program Sample01.scala:

The following is the Scala program named Sample02.scala:

Sample02.scala
/*
 *
 * Name  : Sample02
 * 
 * Author: Bhaskar S
 *  
 * Date  : 01/09/2015
 *  
 */

package com.polarsparc.scala

import scala.util._

object Sample02 {
  def sum(n: Int): Int = {
    var s = 0;
    for (i <- 1 to n) {
      s += i
    }
    return s
  }
  
  def hello(name: String, title: String = "Mr"): Unit = {
    println("Hello " + title + " " + name)
  }
  
  def identify(what: String): Any = {
    what match {
      case "one" => 1
      case "two" => 2
      case "three" => 3.0
      case "red" => "Color RED"
      case "blue" => "Color BLUE"
      case "green" => "Color GREEN"
      case _ => "Unknown"
    }
  }
  
  def toInt(str: String): Option[Int] = {
    try {
      Some(Integer.parseInt(str))
    } catch {
      case ex: NumberFormatException => None
    }
  }
  
  def main(args: Array[String]): Unit = {
    val random: Random = new Random
    
    val xyz = random.nextInt(5)
    val msg = xyz match {
      case 1 => "one"
      case 2 => "two"
      case 3 => "three"
      case _ => "zero or four <" + xyz + ">"
    }
    println("msg = " + msg)
    
    println("sum = " + sum(5))
    
    hello("John")
    hello("Alice", "Mrs")
    
    println("Identify(two) = " + identify("two"))
    println("Identify(three) = " + identify("three"))
    println("Identify(blue) = " + identify("blue"))
    println("Identify(car) = " + identify("car"))
    
    val txt1: Option[String] = Some("Howdy")
    val txt2: Option[String] = None
    
    println("txt1 = " + txt1.get)
    try {
      println("txt2 = " + txt2.get)
    } catch {
      case ex: NoSuchElementException => println("txt2 = None")
    }
    println("txt2 = " + txt2.getOrElse("???"))
    
    val str1 = "25"
    val num1 = try {
      Some(Integer.parseInt(str1))
    } catch {
      case ex: NumberFormatException => None
    }
    println("num1 = " + num1.toString())
    
    val str2 = "25s"
    val num2 = try {
      Some(Integer.parseInt(str2))
    } catch {
      case ex: NumberFormatException => None
    }
    println("num2 = " + num2.toString())
    
    println("toInt = " + toInt("30"))
    println("toInt = " + toInt("30s"))
    
    val str3: Option[String] = Some("100")
    try {
      Integer.parseInt(str3.get)
    } catch {
      case ex: NoSuchElementException => println("str3 is empty")
      case ex: NumberFormatException => println("str3 is not a number")
    } finally {
      println("Done !!!")
    }
  }
}

Executing the program Sample02.scala results in the output:

Output (Sample02.scala)

sum = 15
Hello Mr John
Hello Mrs Alice
Identify(two) = 2
Identify(three) = 3.0
Identify(blue) = Color BLUE
Identify(car) = Unknown
txt1 = Howdy
txt2 = None
txt2 = ???
num1 = Some(25)
num2 = None
toInt = Some(30)
toInt = None
Done !!!

The following section explains some of the aspects of the Scala program Sample02.scala:

The following is the Scala program named Sample03.scala:

Sample03.scala
/*
 *
 * Name  : Sample03
 * 
 * Author: Bhaskar S
 *  
 * Date  : 01/09/2015
 *  
 */

package com.polarsparc.scala

object Sample03 {
  def main(args: Array[String]) = {
    val num1 = -20
    printf("num1 = %d, absolute value of num1 = %d\n", num1, num1.abs)
    
    val num2 = 30.5f
    printf("num2 = %.1f, round value of num2 = %d\n", num2, num2.round)
    
    val text = "hello scala"
    printf("Length of text = %d\n", text.length)
    printf("Capatitize of text = %s\n", text.capitalize)
    printf("Reverse of text = %s\n", text.reverse)
    printf("3 copies of text = %s\n", text * 3)
    printf("Drop first 6 characters of text = %s\n", text.drop(6))
    printf("Drop last 6 characters of text = %s\n", text.dropRight(6))
    printf("Take first 5 characters of text = %s\n", text.take(5))
    
    println(s"<1> We have two numbers : $num1 and ${num2}.\nAnd a string '$text'")
    println(f"<2> We have two numbers : ${num1} and ${num2}%.2f.\nAnd a string '${text}'")
    
    val colors: Array[String] = new Array[String](5)
    colors(0) = "LiteBlue"
    colors(1) = "LiteGreen"
    colors(2) = "LiteOrange"
    colors(3) = "LiteRed"
    colors(4) = "LiteYellow"
    for (i <- 0.until(colors.length)) {
      printf("[1] Color(%d) = %s\n", i, colors(i))
    }
    for (i <- 0.to(colors.length-1)) {
      printf("[2] Color(%d) = %s\n", i, colors.apply(i))
    }
    colors(0) = "Blue"
    colors(1) = "Green"
    colors(2) = "Orange"
    colors(3) = "Red"
    colors(4) = "Yellow"
    for (i <- 0.until(colors.length)) {
      printf("[3] Color(%d) = %s\n", i, colors(i))
    }
    for (i <- 0.until(colors.length)) {
      colors.update(i, "Dark"+colors(i))
    }
    for (i <- 0.until(colors.length)) {
      printf("[4] Color(%d) = %s\n", i, colors(i))
    }
    
    val numbers = Array( "One", "Two", "Three", "Four", "Five")
    for (i <- 0.until(numbers.length)) {
      printf("[5] Number(%d) = %s\n", i, numbers(i))
    }
  }
}

Executing the program Sample03.scala results in the output:

Output (Sample03.scala)

num1 = -20, absolute value of num1 = 20
num2 = 30.5, round value of num2 = 31
Length of text = 11
Capatitize of text = Hello scala
Reverse of text = alacs olleh
3 copies of text = hello scalahello scalahello scala
Drop first 6 characters of text = scala
Drop last 6 characters of text = hello
Take first 5 characters of text = hello
<1> We have two numbers : -20 and 30.5.
And a string 'hello scala'
<2> We have two numbers : -20 and 30.50.
And a string 'hello scala'
[1] Color(0) = LiteBlue
[1] Color(1) = LiteGreen
[1] Color(2) = LiteOrange
[1] Color(3) = LiteRed
[1] Color(4) = LiteYellow
[2] Color(0) = LiteBlue
[2] Color(1) = LiteGreen
[2] Color(2) = LiteOrange
[2] Color(3) = LiteRed
[2] Color(4) = LiteYellow
[3] Color(0) = Blue
[3] Color(1) = Green
[3] Color(2) = Orange
[3] Color(3) = Red
[3] Color(4) = Yellow
[4] Color(0) = DarkBlue
[4] Color(1) = DarkGreen
[4] Color(2) = DarkOrange
[4] Color(3) = DarkRed
[4] Color(4) = DarkYellow
[5] Number(0) = One
[5] Number(1) = Two
[5] Number(2) = Three
[5] Number(3) = Four
[5] Number(4) = Five

The following section explains some of the aspects of the Scala program Sample03.scala: