The Scala Chronicles: The Beginning

The Scala Chronicles: The Beginning

The Scala Chronicles: The Beginning

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"

If 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.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Java and Scala: Why Should You Learn Scala?

Java is a general purpose object oriented language. Scala is less readable due to nested code. The process of compiling source code into byte code is slow. ... Scala treated everything as an instance of the class and it is more object oriented language as compare to Java.

What I Did Not Know About Scala And Its Standard Library

I am working with Scala as my main programming language for about three years now. I recently went through some basic&nbsp;<a href="https://www.scala-exercises.org/std_lib" target="_blank">Scala language exercises</a>&nbsp;for fun and discovered some features and possibilities I did not know about.

Functions and Typeclasses in Scala

Do you want to write functions in a strict Functional Scala manner which is pure, total, and deterministic. Typeclass is the implementation for algebraic structure like Functor and Monad. Typeclass is similar to interface in Object Oriented (OO) programming. How does this feature benefits you?