Variables and functions
The backbone of the Scala language is variables and functions.
The variables are defined as follows:
scala> var foo = 3 foo: Int = 3
Variables are defined using the var
keyword followed by the name of the variable, followed by the value you would like to assign to the variable.
Variables defined in the preceding manner are mutable. This means that once they are assigned, you can modify them:
scala> var foo = 3 foo: Int = 3 scala> foo = 20 foo: Int = 20
However, purely functional programming advocates against this style. Since Scala positions itself as a mixture of purely functional and object-oriented styles, it offers a way to define an immutable variable:
scala> val bar = 3 bar: Int = 3
Now, if you try to modify is this variable, you will get a compile-time error:
scala> val bar = 3 bar: Int = 3
scala> bar = 20 <console>:12: error: reassignment to val bar = 20
Besides all of these, Scala has a similar syntax for functions:
scala> def square(x: Int) = x * x square: (x: Int)Int scala> square(10) res0: Int = 100 scala> square(2) res1: Int = 4
So, a function is just like a value. However, it can be parameterized by arguments, and it will evaluate every time you call it. A normal value is evaluated only once.
Value can be modified with a lazy
attribute to make it lazily evaluated:
scala> val x = { println("x value is evaluated now"); 10 } x value is evaluated now x: Int = 10 scala> lazy val x = { println("x value is evaluated now"); 10 } x: Int = <lazy> scala> x x value is evaluated now res2: Int = 10
When you do find this way, it is not evaluated right away but at the time when it is called for the first time. In a sense, it is similar to a function in this manner, because it is not evaluated right away. However, a function is evaluated every time we call it, and this can be not said of a value.
In the preceding code, all of their definitions are specified without the types they return. However, Scala is a strongly typed language. The compiler knows the types of all its variables. The compiler of Scala is powerful, and it can infer the types of its values and variables in a wide range of circumstances so that you do not need to provide them explicitly. So, in the preceding code, the compiler infers the types of the values, variables, and functions.
You can explicitly specify the type you would like a variable to have as follows:
scala> var x: Int = 5 x: Int = 5 scala> var x: String = 4 <console>:11: error: type mismatch; found : Int(4) required: String var x: String = 4 ^ scala> val x: Int = 5 x: Int = 5 scala> def square(x: Int): Int = x * x square: (x: Int)Int
Also, notice that when you run the code without an explicit type specification through a Scala interpreter, the result will be aware of the type.