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 Data types

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 TypeDefault ValueSize
BooleanFalseTrue or false
Byte08 bit signed value (-27 to 27-1)
Short016 bit signed value(-215 to 215-1)
Char‘\u0000’16 bit unsigned Unicode character(0 to 216-1)
Int032 bit signed value(-231 to 231-1)
Long0L64 bit signed value(-263 to 263-1)
Float0.0F32 bit IEEE 754 single-precision float
Double0.0D64 bit IEEE 754 double-precision float
StringNullA 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

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...