Object Casting in Scala
Last Updated :
03 Jun, 2022
Improve
In order to cast an Object (i.e, instance) from one type to another type, it is obligatory to use asInstanceOf method. This method is defined in Class Any which is the root of the scala class hierarchy (like Object class in Java). The asInstanceOf method belongs to concrete value members of Class Any which is utilized to cast the receiver Object.
Applications of asInstanceof method
- This perspective is required in manifesting beans from an application context file.
- It is also used to cast numeric types.
- It can even be applied in complex codes like communicating with Java and sending it an array of Object instances.
Examples of casting using asInstanceof method
- Casting from Integer to Float.
Example :
Scala
// Scala program of Object Casting // Int to Float case class Casting(a : Int) // Creating object object GfG { // Main method def main(args : Array[String]) { val a = 10 // Casting value of a into float val b = a.asInstanceOf[Float] println( "The value of a after" + " casting into float is " + b) } } |
Output:
The value of a after casting into float is 10.0
- Here, type of ‘a’ is Integer and after casting type will be Float, it is the example of Casting numeric types.
- Casting from Character to Integer.
Example :
Scala
// Scala program of Object Casting // Char to Int case class Casting(c : Char) // Creating object object GfG { // Main method def main(args : Array[String]) { val c = 'c' // Casting value of c into Int val d = c.asInstanceOf[Int] println( "The value of c after" + " casting into Integer is " + d) } } |
Output:
The value of c after casting into Integer is 99
- Here, type of ‘c’ is character and after casting type will be integer, which gives ASCII value of ‘c’.
- Casting from Float to Integer.
Example :
Scala
// Scala program of Object Casting // Float to Int case class Casting(a : Float, b : Float) // Creating object object GfG { // Main method def main(args : Array[String]) { val a = 20.5 val b = 10.2 // Casting value of c into Int val c = (a/b).asInstanceOf[Int] println( "The value of division after" + " casting float into Integer will be " + c) } } |
Output:
The value of division after casting float into Integer will be 2
- Here, type of ‘a’ and ‘b’ is float but after Casting type will be float.