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.


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. 
  println("In loop!") 
  n -= 1 

Do-While Loop

var n = 10 
  * Exit Controlled 
  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 with a step size of 1. for a step 
  *size of 2 specify the step size like:,2) 
for ( i <- 1 to 10) 

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) 

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.


Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

A Beginner's Guide to Scala 3.0

Reading Time: 5 minutes This post describes what to expect and how to start with Scala 3 Or Dotty. In this post, we will get a teaser of what changes to expect from Dotty as well as some of the new changes in the major release. At the end of the post, we will see how we can quickly start with the Dotty compiler and example code.

Use of Either in Scala

In this blog, we are going to see the use of Either in scala. We use Options in scala but why do we want to go for Either? Either is a better approach in the respect that if something fails we can track down the reason, which in Option None case is not possible. We simply pass None but what is the reason we got None instead of Some. We will see how to tackle this scenario using Either.

Understanding Higher-Order functions in Scala

Reading Time: 4 minutes A blog on using higher-order functions in Scala.A higher-order function is a function that takes in another function as argument and itself returns some value or function. Some examples of higher-order functions include map, filter, reduce, foreach etc.

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.

Exception handling in Scala

Scala is functional programming language. Except for the side effects that have a return type of Unit or (), everything else returns a value in scala. Scala treats everything as an expression and that is what makes scala such a powerful language.