Scala – Data Types
In this tutorial, we will see the data types used in scala.
What is a data type?
A data type is a categorisation of data that tells compiler what type of value the variable holds e.g. if a variables has INT data type, then we can say that variable is having numeric value.
Data types in scala are almost similar to java in terms of length and storage. There is no concept of primitive data type like in java, every type is an object and starts with capital letter. It has the below parent child relationship.
Scala Null: This refers to an empty or null reference.
Scala Nothing: Nothing is a subtype to every other type and it holds no value at all. So, where would we use it? We can use it to signal non-termination like a thrown exception, program exit, or an infinite loop.
Scala Any: This is the supertype for all other types. This means that any object is of the type Any.
Scala AnyRef: AnyRef represents reference types. Since all these Scala Data types are objects and not primitives, it is possible to call methods on these objects.
Scala AnyVal: This represents value types.
You can also understand their storage range and default value with the help of below table.
|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|
We can use data types as shown below. Variable a, b and c are having data types as Boolean, Int and Double respectively.
scala> var a: Boolean = true a: Boolean = true scala> var b: Int = 4 b: Int = 4 scala> var c:Double = 2.58498 c: Double = 2.58498