Scala Quick Notes :: Part - 1
Bhaskar S | 01/09/2015 |
Overview
Scala is a modern general purpose hybrid programming language with the following characteristics:
Functional
Object Oriented
Statically Typed
Compiles to Java Byte Code
Runs on a JVM
Setup
Download and install the following software:
Java SE Runtime (www.oracle.com/technetwork/java/javase/downloads/index.html)
Scala Programming Language (www.scala-lang.org/download/)
Scala IDE for Eclipse (scala-ide.org)
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:
NOTE :: Scala program files have the extension ".scala"
Executing the program Sample01.scala results in the output:
<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:
Use _ as the wildcard character in the import statement
Ex: import scala.util._
Use the keyword object to define a singleton object
Use the template variable-or-parameter: type[generic] to define a variable or method parameter of a generic type. In this example, the main method takes one parameter called args which is an array of String
Ex: args: Array[String]
Ex: a: Int
Use the template def main(args: Array[String]): Unit = { body } to define the main method
One need not specify a data type for a variable as Scala will automatically try to determine the type based on the context
Ex: var b = 0
Everything is an object in Scala, including primitive type such as Int, Float, Long, Double, String, etc
The String operation + used for concatenation is actually a method call String.+(String)
Ex: "<2> a = ".+(a)
Use the keyword var to define a mutable variable and the keyword val to define an immutable variable
Ex: var b = 0
Ex: val c = 5
Use the template for (variable <- range-or-collection) { body } to define a for loop
Ex: for (i <- 1 to 5) {}
The expression 1 to 5 products a range (or list) of numbers from 1 through 5
The expression 1 to 5 is actually a method call on the number 1 1.to(5)
The expression 1 until 5 products a range (or list) of numbers from 1 upto 4 (not inclusive of 5)
The expression 1 until 5 is actually a method call on the number 1 1.until(5)
Use the template for {variable1 <- range1-or-collection1; variable2 <- range2-or-collection2} { body } to define a for loop that has the same effect as a for loop inside a for loop
Ex: for {i <- 1 to 3; j <- 1 to 3} {}
Use the template for {variable <- range-or-collection; if condition} { body } to define a for loop that filters out values that do not satisfy the if condition
Ex: for {i <- 1 to 10; if i %2 == 0} {}
In Scala, an output of an if .. else if .. else expression can be assigned to a variable
Ex: val d = if (c > 0) 5 else -5
In Scala, an output from a block of statements { statements } can be assigned to a variable
Ex: val e = { val x = 3; val y = 5; ((x*x) + (y*y)) }
The following is the Scala program named Sample02.scala:
Executing the program Sample02.scala results in the output:
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:
Use the template def method(parameters): return-type = { body } to define a method
Ex: def sum(n: Int): Int = {}
Use the keyword Unit to define a void return type
Ex: def greetings(name: String): Unit = {}
A method parameter can specify a default value, which allows the caller to omit that parameter when calling the method
Ex: def hello(name: String, title: String = "Mr"): Unit = {}
Use the keyword Any to define a data type that can take any type
Ex: def identify(what: String): Any = {}
Pattern matching uses the keyword match followed by various case expressions.
Think of it as similar to a switch statement in Java but much more powerful.
case _ is the wildcard match and similar to default in Java switch.
Use the template variable match {case expr-1 => statement-1; case expr-2 => statement-2;...} to define a Scala pattern matching statement
Ex: xyz match { case 1 => "one"; case 2 => "two"; case 3 => "three"; case _ => "others" }
Use the keyword Option[T] to wrap a value of type T that could either be present or absent. When the value of Option[T] is a None, it means no value. And, when the value of Option[T] is a Some(value), it means it has some value
Ex: val txt1: Option[String] = Some("Howdy")
Ex: val txt2: Option[String] = None
The method get() on a Option[T] returns the wrapped value of type T. If the value is not present, throws a NoSuchElementException
Ex: txt1.get
The method getOrElse(default-value) on a Option[T] returns the wrapped value of type T. If the value is not present, returns the specified default-value
Ex: txt2.getOrElse("???")
The try {...} catch {...} finally {...} is similar to that in Java except that the catch part uses pattern matching
Ex: 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 !!!") }
The following is the Scala program named Sample03.scala:
Executing the program Sample03.scala results in the output:
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:
Use Scala string interpolation to perform variable substitution by embedding variables directly in string literals.
To use string interpolation, precede the string literal with the letter s and then embed variable names preceded by a $ symbol. The variable can optionally surrounded by curly braces {}
Ex: s"We have two numbers : $num1 and ${num2}.\nAnd a string '$text'"
To use printf like formatting in string interpolation, precede the string literal with the letter f and then embed variable names preceded by a $ symbol followed by the formatting element. The variable can optionally surrounded by curly braces {}
Ex: f"We have two numbers : ${num1} and ${num2}%.2f.\nAnd a string '${text}'"
To access the i'th element of an array xyz, use the format xyz(i). Under the hood Scala invokes the method apply. In other words, xyz(i) is the same as xyz.apply(i)
Ex: printf("[1] Color(%d) = %s\n", i, colors(i))
Ex: printf("[2] Color(%d) = %s\n", i, colors.apply(i))
To update the i'th element of an array xyz with value V, use the format xyz(i) = V. Under the hood Scala invokes the method update. In other words, xyz(i) = V is the same as xyz.update(i, V)
Ex: colors(0) = "Blue"
Ex: colors.update(i, "Dark"+colors(i))