Type Casting in Scala

A Type casting is basically a conversion from one type to another. In Dynamic Programming Languages like Scala, it often becomes necessary to cast from type to another.Type Casting in Scala is done using the asInstanceOf[] method.

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.

Syntax:
obj1 = obj.asInstanceOf[class];

where,
obj1 is the object to which the casted instance of obj is returned,
obj is the object to be casted, and
class is the name of the class to which obj is to be casted into.

Here, only an object of an extended(child) class can be casted to be an object of its parent class but not vice-versa. If class A extends class B, A’s object can be cast to be an object of class B and B’s object canot be cast to be an object of class A. This method informs the compiler that the value is of the type specified. During runtime, if the value/object supplied is not compatible with the type or class specified, an exception is thrown.

Examples:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of type casting
object GFG
{
    // Function to display name, value and 
    // class-name of a variable
    def display[A](y:String, x:A) 
    {
        println(y + " = " + x + " is of type "
                            x.getClass.getName);
    }
      
    // Main method
    def main(args: Array[String])
    {
        var i:Int = 40;
        var f:Float = 6.0F;
        var d:Double = 85.2;
        var c:Char = 'c';
          
        display("i", i);
        display("f", f);
        display("d", d);
        display("c", c);
          
        var i1 = i.asInstanceOf[Char]; //Casting
        var f1 = f.asInstanceOf[Double]; //Casting
        var d1 = d.asInstanceOf[Float]; //Casting
        var c1 = c.asInstanceOf[Int]; //Casting
  
        display("i1", i1);
        display("f1", f1);
        display("d1", d1);
        display("c1", c1);
    }
}

chevron_right


Output:

i = 40 is of type java.lang.Integer
f = 6.0 is of type java.lang.Float
d = 85.2 is of type java.lang.Double
c = c is of type java.lang.Character
i1 = ( is of type java.lang.Character
f1 = 6.0 is of type java.lang.Double
d1 = 85.2 is of type java.lang.Float
c1 = 99 is of type java.lang.Integer

Examples:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of type casting
  
// The parent class
class Parent 
{
    var i: Int = 10;
    var j: Int = 5;
      
    // Function to display i and j values
    def display() 
    {
        println("Value of i : " + i + 
                "\nValue of j : " + j); 
    }
}
  
// The child class
class Child extends Parent 
{
    // Used to change i and j values
    def change() 
    {
        i = 6;
        j = 12;
        println("Values Changed");
    }
}
  
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
        var c:Child = new Child();
        c.display();
        c.change();
          
        // Casting
        var p:Parent = c.asInstanceOf[Parent]; 
        p.display();
          
        /* p.change(); This will have raised an error
        as p is seen as an object of class Parent and
        Parent does not contain change() */
    }
}

chevron_right


Output:

Value of i : 10
Value of j : 5
Values Changed
Value of i : 6
Value of j : 12

In above example p.change(); will be added, the following error would have been occured:

error:value change is not a member of parent.

Examples:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of type casting
  
class Parent
{
    // Member variables and functions.     
}
  
class Child extends Parent
{
    // Member variables and functions.     
}
  
class Unrelated
{
    // Member variables and functions.     
}
  
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
        var p:Parent = new Parent();
        try
        {
            p.asInstanceOf[Unrelated];
        }
        catch
        {
            // Used to print the thrown exception.
            case e: Exception => e.printStackTrace(); 
                        print(e);
        }
        try
        {
            p.asInstanceOf[Child];
        }
        catch
        {
            // Used to print the thrown exception.
            case e1: Exception => e1.printStackTrace(); 
                        print(e1);
        }
    }
}

chevron_right


Output:

java.lang.ClassCastException: Parent cannot be cast to Unrelated
java.lang.ClassCastException: Parent cannot be cast to Child


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.