The Scala Chronicles: The Beginning.

Reading Time: 4 minutes

This is the beginning of a multi-part series on Scala. Starting with an introduction to usage of var and `val` followed by Control Structures. If you have some prior programming experience, you’d feel right at home. If not, I’ll try to introduce the concepts in a way that you’d understand.

Declaring “var”, or maybe not!

Scala allows one to declare variables mutable or immutable. Immutable objects cannot be modified after they are created. This is in contrast to a mutable object, which can be modified after it is created.

Scala has two kinds of variables, vals(Similar to a final variable in Java) and vars(Similar to a non-final variable in Java). Once initialized, a val can never be reassigned. A var, by contrast, can be reassigned throughout its lifetime.

Scala> var mutableObject = "This is a String
mutableObject: String = This is a String

Scala> mutableObject = "This is also a String"
mutableObject: String = This is also a String

In Scala, you are encouraged to use a val unless you absolutely need to change the contents. Immutability is a good thing for many reasons. One of them is: If an object doesn’t change internal state, you don’t have to worry if some other part of your code is changing it. This becomes particulary important with multithreaded systems.

Simply put, using val is safer and leads to more readable code.

scala> val immutableObject = "Immutability is good"
immutableObject: String = Immutability is good

scala> immutableObject = "Changed value"
<console>:12: error: reassignment to val
       immutableObject = "Changed value"

I f you try to reassign an immutable object, the Scala compiler will throw an error.

The All Knowing: Type Inference in Scala

The Scala compiler has the ability to figure out types you leave off. A local type inference mechanism takes care that the user is not required to annotate the program with redundant type information. Operations that break type constraints leads to compiler errors, not run time errors.

An Extra Cookie: When the Scala Interpreter(or compiler) can infer types, it is often best to let it do so rather than fill in the code with unnecessary, explicit type annotations.

You can, however, specify a type if you wish.

scala>  val greetings: String = "Hello!"
greetings: String = Hello!

Control Your Battles: Control Structures

One of the important aspects of programming is the ability to express logic in our programs. We want to be able to control the way our program executes, and that’s where control structures come in.

A control structure is a block of programming that analyses variables and selects how to proceed based on certain parameters. You will encounter a fundamental difference between Scala and other programming languages.
In Java or C++, we differentiate between expressions and statements.

Expressions: have a value and a type.
Statements: carry out an action.

Conditional Expressions

Scala has an if/else construct with the same syntax as in Java. However, an if/else has a value(Expression): The value of the expression that follows the if or else.
Scala’s if/else are similar to the ternary operator in Java{ (condition)?(result 1): (result 2) }. However, you can’t put statements inside it. But, the Scala if/else combines the if/else and ?: constructs that are separate in Java.

For Example: for some variable count with a value of 25, the following expression is perfectly legal.

scala> val str = if(x>25) "Get in, Have a drink" else "Sorry!"
str: String = Get in, Have a drink

Every expression has a type, like in the example above, both branches of the construct have the type String. For a mixed expression, the type of expression would be the common supertype of both data-types.

scala> val x=27
x: Int = 27

scala> if (x>25) "Get in, Have a drink!" else -1
res2: Any = Get in, Have a drink!

The type of the this expression would be the common super type Any.

Loops

Scala has the same while and do-while loops as Java. Let’s start off with an example of while loop, followed by an example of a do-while loop.

While Loop

var n = 10
/*
 *Entry controlled loop. Condition checked first.
 */
while(n>0)
{
    println("In loop!") 
    n -= 1            
}

Do-While Loop

var n = 10
/*
 * Exit Controlled
 */
do
{
    println("In Loop") 
    n-=1
}while(n>0)

For Loop

Scala has no direct analogue of the `for  construct` that we are familiar with(How’s it going Java programmers?). If you need such a loop, you can use a for statement like this:

/*
 *Similar to calling 1.to(10) with a step size of 1. for a step 
 *size of 2 specify the step size like: 1.to(10,2)
 */
for ( i <- 1 to 10) 
{                  
   println(i)     
}

To emulate the less than operator(<), type in the following:

/*
 *Equivalent to using the <= operator in looping. Also, you can 
 *specify the step size.
 */
for( i <- 1 until 10) 
{                    
    println(i)     
}

Advanced For Loop(Comprehensions)

Comprehensions have the below form.

scala> val a = for(i<- 1 to 10 if(i%2)==0) yield i*2
a: scala.collection.immutable.IndexedSeq[Int] = Vector(4, 8, 12, 16, 20)

The above for comprehension would result in a vector{ Vector(4,8,12,16,20) }. The <- is called a generator, the if construct is the guard condition{filter}, yield constructs a collection of values. This type of for loop is called a for comprehension

That’s it for this blog, then. Here’s hoping that you find this blog helpful. Please, comment below and let us know if the blog was helpful to you in any way or the topics that you’d want us to cover in the future.

References:

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading