Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Source

Scala language - the basics

Scala is a statically typed language with a very expressive type system which enforces abstractions in a safe yet coherent manner. All values in Scala are Java objects (primitives which are unboxed at runtime), because at the end of the day, Scala runs on the Java JVM. Scala enforces immutability as a core FP principle. This enforcement happens in multiple aspects of the Scala language, for instance, when you create a variable, you do it in an immutable way, when you use an collection, you will use a immutable collection. Scala also lets you use mutable variables and mutable structures, but by design, it favors immutable ones.

Scala variables - var and val

When you are coding in Scala, you create variables using the operator var, or you can use the operator val. The operator var allows you to create a mutable state, which is fine as long as you make it local, follow the CORE-FP principles and avoid a mutable shared state.

Scala REPL var usage

We will see how to use var in Scala REPL as follows:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>var x = 10

x: Int = 10

scala>x

res0: Int = 10

scala>x = 11 x: Int = 11 scala>x res1: Int = 11 scala>

However, Scala has a more interesting construct called val. Using the val operator makes your variables immutable, and this means you can't change the value once you've set it. If you try to change the value of the val variable in Scala, the compiler will give you an error. As a Scala developer, you should use the variable val as much as possible, because that's a good FP mindset, and it will make your programs better. In Scala, everything is an object; there are no primitives — the var and val rules apply for everything it could but an Int or String or even a class.

Scala val usage at the Scala REPL

We will see how to use val in Scala REPL as follows:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>val x = 10

x: Int = 10

scala>x

res0: Int = 10

scala>x = 11

:12: error: reassignment to val x = 11

A

scala>x res1: Int = 10 scala>

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics