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.
Example :// Scala program of Object Casting// Int to FloatcaseclassCasting(a:Int)// Creating objectobjectGfG{// Main methoddefmain(args:Array[String]){vala=10// Casting value of a into floatvalb=a.asInstanceOf[Float]println("The value of a after"+" casting into float is "+ b)}}chevron_rightfilter_noneOutput: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 program of Object Casting// Char to IntcaseclassCasting(c:Char)// Creating objectobjectGfG{// Main methoddefmain(args:Array[String]){valc='c'// Casting value of c into Intvald=c.asInstanceOf[Int]println("The value of c after"+" casting into Integer is "+ d)}}chevron_rightfilter_noneOutput: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 program of Object Casting// Float to IntcaseclassCasting(a:Float, b:Float)// Creating objectobjectGfG{// Main methoddefmain(args:Array[String]){vala=20.5valb=10.2// Casting value of c into Intvalc=(a/b).asInstanceOf[Int]println("The value of devision after"+" casting float into Integer will be "+ c)}}chevron_rightfilter_noneOutput:The value of devision after casting float into Integer will be 2
Here, type of ‘a’ and ‘b’ is float but after Casting type will be float.
Recommended Posts:
- Type Casting in Scala
- Class and Object in Scala
- Object Equality in Scala
- Scala | Stateful Object
- Determine the class of a Scala object
- Scala | Case Class and Case Object
- How to check a JavaScript Object is a DOM Object ?
- HTML | DOM Object Object
- Set in Scala | Set-1
- Scala | Either
- Set in Scala | Set-2
- Scala Map
- Scala | Multithreading
- Scala For Comprehensions
- Monads in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



