Scala Type Casting

In this tutorial, we will learn about the various types of type casting with examples in Scala. By Shivang Yadav Last updated : April 02, 2023

Types in Scala

Type also know as data type tells the compiler about the type of data that is used by the programmer. For example, if we initialize a value or variable as an integer the compiler will free up 4 bytes of memory space and it will hold 32 bit signed integer type.

Type Casting in Scala

Type casting is the process of converting that type from one to another. For example, We can convert int type to float type in Scala.

But this conversion cannot be two ways and is derived from certain types i.e. the conversion from one type to another is possible and the reverse is not. This is due to the different sizes of data type and conversion from type of size greater to a smaller one might lead to data losses.

Type Casting Conversion

The following diagram shows which conversion is possible:

Scala | Type Casting

Know more about type hierarchy: Scala type hierarchy.

The following conversions are valid:

Character -> Integer
Short -> Integer
Byte -> Integer
Integer -> Long
Long -> Float 
Float -> Double

But, the reverse conversions can be done but are invalid due to data losses. For example, Double -> Float is invalid.

Types of Type Casting

There can be two types of typecasting as all programming languages have,

  1. Implicit type casting
  2. Explicit type casting

1) Implicit type casting

In implicit type Casting of type in Scala the compiler itself cast the type of the value/variable. This conversion can be lossy i.e. in some cases data may be lost. For example, in the case of division of two int values which can return a non-integer (float/ double) value, the result will be of integer type which can lead to data loss.

Scala example of implicit type casting

object MyClass {
  def main(args: Array[String]): Unit = {
    val a: Int = 3421
    println("a has value: " + a + " and its type is: " + a.getClass)
    val c = a / 4 // result is 855.25 but will be converted to Int
    println("The value of a/4: " + c + " and its type is: " + c.getClass)
  }
}

Output

a has value: 3421 and its type is: int
The value of a/4: 855 and its type is: int

In the above code, we have created a value a of type integer with value 3421, then we have divided a by 4 and stored the result in value c.  This division leaves to a decimal point value but due to implicit type conversion, it is stored in integer type which two losses.

This problem can be solved by using explicit conversion to avoid data loss but in some cases that may lead to excessive memory wastage.

2) Explicit Type Conversion

The explicit type conversion is user-defined type conversion i.e. the user will decide that final data type of the value/variable.

The type conversion of value types can be done directly but for reference types, the conversion required asInstanceOf method.

As the asInstanceOf method is a concrete method of Any Class, it can be used for type conversion of AnyVal object and AnyRef objects too (object conversion).

Let's see the examples of both the methods in action:

Scala example of explicit type casting

object MyClass {
  def main(args: Array[String]): Unit = {
    // Type conversion from Short to Long
    val a: Short = 3421
    println("a has value: " + a + " and its type is: " + a.getClass)
    val b: Long = a // converting type from short to long
    println("Type casting from Short to Long")
    println("b has value: " + b + " and its type is: " + b.getClass)

    // Type conversion from Char to Float
    val ch: Char = 'S'
    println("\nch has value: " + ch + " and its type is: " + ch.getClass)
    val fl: Float = ch // converting type from Char to Float
    println("Type casting from Character to Float")
    println("fl has value: " + fl + " and its type is: " + fl.getClass)
  }
}

Output

a has value: 3421 and its type is: short
Type casting from Short to Long
b has value: 3421 and its type is: long

ch has value: S and its type is: char
Type casting from Character to Float
fl has value: 83.0 and its type is: float

In the above code, we have done two types of conversions. One from short to long and other from char to float.

For short to long, we have created variable a of type short that stores a value 3421, and then we have created another variable b of type long which is initialized with the value of short.

For char to float, we have created variable ch of type char that stores a value S, and then we have created another variable fl of type float which is initialized with the value of char. This will have the float type of ASCII value of 'S'.

Scala example of explicit type casting using asInstanceOf method

object MyClass {
  def main(args: Array[String]): Unit = {
    // Type conversion from Short to Flaot
    val a: Short = 3421
    println("a has value: " + a + " and its type is: " + a.getClass)
    val b = a.asInstanceOf[Double] // converting type from short to long
    println("Type casting from Short to Double")
    println("b has value: " + b + " and its type is: " + b.getClass)

    // Type conversion from Char to Int
    val ch: Char = 'S'
    println("\nch has value: " + ch + " and its type is: " + ch.getClass)
    val intVal = ch.asInstanceOf[Int] // converting type from Char to Int
    println("Type casting from Character to Int")
    println(
      "intVal has value: " + intVal + " and its type is: " + intVal.getClass
    )
  }
}

Output

a has value: 3421 and its type is: short
Type casting from Short to Double
b has value: 3421.0 and its type is: double

ch has value: S and its type is: char
Type casting from Character to Int
intVal has value: 83 and its type is: int

In the above code, we have done two types of conversions. One from short to Double and other from char to int.

For short to Double, we have created variable a of type short that stores a value 3421, and then we have created another variable b of type Double which is initialized using the asInstanceOf method for conversion of type.

For char to float, we have created variable ch of type char that stores a value S, and then we have created another variable intVal of type int which is initialized with the value of char using the asInstanceOf method. The data in the intVal is the ASCII value for the character.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.