Sometimes we find ourselves in a situation where we need the value of an already existing variable in a different data type than the one with which it was defined. This is where type casting comes in. Type casting is an approach which allows changing the data type of a variable or an expression from one to another.
One thing to remember is that not every data type can be converted to a data type of choice. Let’s look at the type casting flow in Scala to better understand which data type can be converted to which data type.
The arrows in the above diagram are giving the direction of conversion. For example, a Float can be converted to a Double, but a Double cannot be converted to a Float. The elements more or less remain the same and the value is simply altered with respect to the new data type.
Let’s look at some examples.