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
case class Casting(a : Int)
object GfG
{
def main(args : Array[String])
{
val a = 10
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
case class Casting(c : Char)
object GfG
{
def main(args : Array[String])
{
val c = 'c'
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
case class Casting(a : Float, b : Float)
object GfG
{
def main(args : Array[String])
{
val a = 20.5
val b = 10.2
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.