Object Casting in Scala
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.
- 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.
- Casting from Integer to Float.
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.
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.
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.