We use data types to define what type of value a variable holds. For example, if we want to declare a variable and assign a number to it, we use the integer, int
, data type.
Similarly, if we want a variable to store textual data, we use the string
data type, which is a collection of characters.
There are several other data types, each of which has its own size.
In Scala, we have various data types similar to what we use in Java or C++. Those data types are:
Integer: This data type holds a numeric value of a maximum of 32-bits. The integer data type has two subtypes:
long: holds a numeric value of maximum 64-bits.
short: holds a numeric value of maximum 16-bits.
String: This data type supports textual data, written inside (""
) double-quotes.
Boolean: We use the boolean
data type in a situation where we want to declare variables that have true
or false
values.
Char: It is short for character. char
only supports a single character written inside (''
) single-quotes.
Float: Also known as floating-point,
this data type is used to store real numbers, that include a fractional part, in a variable that has a capacity of 32-bits.
Double: This data type is similar to Float.
It just holds a max length of 64-bits.
Let’s observe the following example to see how these data types can be implemented in Scala.
// var keyword is used to// declare variables in Scalavar int: Int = 50var short: Short = 40var long: Long = 80var string: String = "Hello World!"var bool: Boolean = truevar char: Char = 'H'var float: Float = 3.142fvar double: Double = 3.141592653589793println("1. integer: " + int)println("2. short: " + short)println("3. long: " + long)println("4. string: " + string)if (bool == true) {println("5. boolean: this is a true value!")}println("6. char: " + char)println("7. float: " + float)println("8. double: " + double)
var
keyword is used to declare variables. To initialize those variables, we write their data types followed by the value we want to store.
println()
is used to display the values of each variable.