VOOZH about

URL: https://www.geeksforgeeks.org/scala/type-casting-in-scala/

⇱ Type Casting in Scala - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Type Casting in Scala

Last Updated : 8 Jun, 2022

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 cannot 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:  

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: 

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 occurred:  

error:value change is not a member of parent.

Examples:  

Output: 

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


 

Comment
Article Tags:
Article Tags:

Explore