This tour contains bite-sized introductions to the basics syntax of Scala. It is intended for newcomers to the language.

Values

You can name results of expressions with the val keyword.

Named results, such as x here, are called values. Referencing a value does not re-compute it.

Values cannot be re-assigned.

Types of values can be inferred, but you can also explicitly state the type, like this:

Notice how the type declaration Int comes after the identifier x. You also need a :.

Variables

Variable is a name which is used to refer memory location. You can create mutable and immutable variable in scala. Let’s see how to declare variable.

Mutable Variable

You can define a Mutable variable with the var keyword.It allows you to change value after declaration of variable.

In the above code, var is a keyword and x is a variable name. It contains an integer value 3. Scala is a type infers language so you don’t need to specify data type explicitly. You can also mention data type of variable explicitly as we have used in below.

Immutable Variable

An immutable variable is declared with the keyword val. This means that it is a variable that cannot be changed.We will create a value with the name x and assigned with a literal number 100.

The above code throws an error because we have changed content of immutable variable, which is not allowed. So if you want to change content then it is advisable to use var instead of val.

Blocks

You can combine expressions by surrounding them with {}. We call this a block.

The result of the last expression in the block is the result of the overall block, too.

Functions

Functions are expressions that take parameters.

You can define an anonymous function (i.e. no name) that returns a given integer plus one:

On the left of => is a list of parameters. On the right is an expression involving the parameters.

Now you will look at the function involving parameters and you can also name functions.

Functions may take multiple parameters.

Or it can take no parameters.

Methods

Methods look and behave very similar to functions, but there are a few key differences between them.

Methods are defined with the def keyword. def is followed by a name, parameter lists, a return type, and a body.

Notice how the return type is declared after the parameter list and a colon : Int.

Methods can take multiple parameter lists.

Classes

You can define classes with the class keyword followed by its name and constructor parameters.

The return type of the method greet is Unit, which says there’s nothing meaningful to return. It’s used similarly to void in Java and C.

You can make an instance of a class with the new keyword.

This is all about basics syntax in Scala.We will cover rest of the topics in next article.Keep Learning and Sharing!! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *