Skip to content
Related Articles

Related Articles

Improve Article
Type Casting in Scala
  • Last Updated : 29 Mar, 2019

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:




// 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);
    }
}

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:




// 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() */
    }
}

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:




// 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);
        }
    }
}

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
Recommended Articles
Page :