Mutable Variable
scala> var a : Int = 120;
var a: Int = 120
scala> a+30;
val res0: Int = 150
scala> a*10
val res1: Int = 1200
scala> a=55;
a: Int = 55
Note: when ever you are given VAR , it is mutable.. we can change the value again
Immutable Variable
scala> val b : Int = 100;
val b: Int = 100
scala> b = 20;
-- [E052] Type Error: ----------------------------------------------------------
1 |b = 20;
|^^^^^^
|Reassignment to val b
Note: when ever you are given VAL , it is immutable.. we can not change the value again.
============================
scala> var c = true;
var c: Boolean = true
scala> var d = 10.55;
var d: Double = 10.55
scala> var d = 12.23f;
var d: Float = 12.23
Note: Scala automatically recognize the data type
=====================
multiple expressions
scala> val x = {val a : Int = 200; val b : Int =100; a+b};
val x: Int = 300
scala> val x = {
| val a: Int = 500;
| val b: Int = 100;
| a-b;
| }
val x: Int = 400
scala> lazy val x = 500;
lazy val x: Int
scala> x * 2;
val res2: Int = 1000
scala> val myVal : String = "Foo";
val myVal: String = Foo
=========================================================================
Program
object Variable {
def main(args: Array[String]) =
var myVar :Int = 10;
val myVal :String = "Hello Scala with datatype declaration.";
var myVar1 = 20;
val myVal1 = "Hello Scala new without datatype declaration.";
println(myVar); println(myVal); println(myVar1);
println(myVal1);
}
Output:
C:\Users\mhtpr\Desktop\SQL.....ETL..Tableau\Materails\scala>scalac Variable.scala
C:\Users\mhtpr\Desktop\SQL.....ETL..Tableau\Materails\scala>scala Variable
10
Hello Scala with datatype declaration.
20
Hello Scala new without datatype declaration.