Additional material for workshops introduction to scala

## Variables

Lets start with basics. A variable in scala is declared like this:

Lets take a look at syntax:

• we start with keyword var (as variable)
• then after a colon we have a variable type
• last but not least we have an equal sign (assignment operator) and the variable value. Important you cannot create a variable without initial value

What might be surprising we can omit the type and write the variable like this:

This is what is called type inference which means that the compiler will find the type of the variable.
What is important when you try to assign something that is not of the original type compilation will fail.

## Values (might be called constant in other languages)

Values are similar to variables with the difference that once set their value cannot be changed. This is a thing called immutability.

## Methods and functions

Like in other programming languages you can define a function (or a method). In scala we have two ways of declaring them:

This way we declare a method called aMethod which accepts an argument called argument of type Int and returns a String which is a result of calling toString method. Please note that no return statement is required. In scala you always return last expression. Similarly to variables and values we can omit returned type because compiler will figure out what is returned basing on the last expression.

To call a method you can use () operator:

Default parameters are created with assignment operator like this:

Scala allows you to use named parameters, which are extremely useful in case you have more than one default parameter:

In scala you can also declare anonymous functions (sometimes called lambda)

For case of simplicity lets suppose that methods and anonymous functions are equal. You can read about the differences here

## Classes

In scala you can define a class using class keyword like this:

In order to create instance of this class you must pass all needed constructor variables using new operator:

Constructor is a method so you can use everything I showed before(default parameters, calling parameters by name).

If we include val in front of constructor variable we will obtain a free getter:

If we include var in front of constructor variable we will obtain a free getter and setter:

We can also create a thing called case class which is an extremely popular concept in scala. Let me show you how it works:

If you want to read more about scala case classes take a look here