Scala Variables and Data Types
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 create mutable variable using var keyword. It allows you to change value after declaration of variable.
In the above code, var is a keyword and data is a variable name. It contains an integer value 100. 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.
Another example of variable
Immutable Variable
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.
Data Types in Scala
Data types in scala are much similar to java in terms of their storage, length, except that in scala there is no concept of primitive data types every type is an object and starts with capital letter. A table of data types is given below. You will see their uses further.
Data Type | Default Value | Size |
---|---|---|
Boolean | False | True or false |
Byte | 0 | 8 bit signed value (-27 to 27-1) |
Short | 0 | 16 bit signed value(-215 to 215-1) |
Char | ‘u0000’ | 16 bit unsigned Unicode character(0 to 216-1) |
Int | 0 | 32 bit signed value(-231 to 231-1) |
Long | 0L | 64 bit signed value(-263 to 263-1) |
Float | 0.0F | 32 bit IEEE 754 single-precision float |
Double | 0.0D | 64 bit IEEE 754 double-precision float |
String | Null | A sequence of characters |