Thursday 14 December 2017

Introduction to Scala - I

The inspiration for a series of posts on gentle introduction to Scala and Python languages was a request from a close friend. For all the work in this post, we will use Read-Evaluate-Print-Loop Scala interpreter. As you may be aware, Scala is a statically typed, object-oriented, functional, and extensible language. Some familiarity with Java will be of great help in understanding Scala. In this post, we will start with a few basic commands.

To invoke the Scala interpreter, type scala on the command line as shown below:

scala

The results returned are shown below:







To print Hello, World!, type the below command:

println("Hello, World!")

The results returned are shown below:

scala> println("Hello, World!")
Hello, World!


To set a value to an immutable variable called x, use below command:

val x = 1

The type is inferred to be integer in the above case. The results are shown below:

scala> val x = 1
x: Int = 1


If  we try to change the value of  x, we get below error:

scala> x = 2
<console>:12: error: reassignment to val
       x = 2
         ^

We can view val more like a constant. To be able to set a type as integer on the val, we can use below command:

val y:Int = 1

The results are shown below:

scala> val y:Int = 1
y: Int = 1


We can add the two constants as shown below:

scala> x+y
res1: Int = 2


In the same way, we can create a variable using var to create a variable whose value can reset:

scala> var a = 1
a: Int = 1

scala> var b:Int = 1
b: Int = 1

scala> a+b
res2: Int = 2


To quit the interpreter, use CTRL + D keys.

The results returned are shown below:

scala> :quit

F:\scala\examples>


To output the same result via a file, we can use below file called fileDemo.scala saved under F:\scala\examples directory the contents of which are as below:

// prints Hello, World!
println("Hello, World!")


Then, to run the command in the file, type below command:

scala fileDemo.scala

The results returned are shown below:

F:\scala\examples>scala fileDemo.scala
Hello, World!


Let us next run a simple program that has a method:

object foobar {
/*Objects are single instances of their own definitions.
  It contains a method called main, the entry point of the program */
  def main(args: Array[String]){
    println("Hello, World!")
    // prints Hello, World
  }
}


In the above program, multiline comments are between /* and */. Single line comments are followed by //. The program has a main method that is the entry point. Save the the contents into a file called methodDemo.scala. Running the file as follows produces the output:

F:\scala\examples>scala methodDemo.scala
Hello, World!


We can also compile the above program with compiler and run it with scala like we do in Java as shown below:

F:\scala\examples>scalac methodDemo.scala

F:\scala\examples>scala -classpath . foobar
Hello, World!


foobar is used as that is classname.

We can also enclose the println command inside a class as shown below:

class SimpleClass {
        println("Hello, World!")
}
val SimpleClass = new SimpleClass


Saving above lines in a file called classDemo.scala and running it gives below result:

F:\scala\examples>scala classDemo.scala
Hello, World!


We can combine expressions using brackets as { ... } as shown below:

scala> { val x = 1
     | val y = 5
     | val z = 3
     | x+y-z
     | }
res2: Int = 3


The result is shown after the closing bracket is entered on the console.

We can also attempt multiple assignments as shown below: 

scala> val (a,b,c,d,e,f,g,h,i) = (1,1L,1F,1D,'a',"String",true,(),null)
a: Int = 1
b: Long = 1
c: Float = 1.0
d: Double = 1.0
e: Char = a
f: String = String
g: Boolean = true
h: Unit = ()
i: Null = null


The above example also shows the different common data types like integer, long, float, double, character, string, boolean, unit and null. All the types are inferred by the interpreter. Unit is a value type which carries no meaningful information. Null is a subtype of all reference types. It has a single value identified by the keyword literal null.

We can define a anonymous function as shown below:

scala> (x: Int) => x * x
res13: Int => Int = <function1>

This function calculates the square of a number. We can assign it to a val as shown below:

scala> val square = (x: Int) => x * x
square: Int => Int = <function1>

scala> square(3)
res14: Int = 9

We then calculate square of 3. 

We will continue in second part of this series.