Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to Create a JSON Object in Scala?
Next article icon

Object Casting in Scala

Last Updated : 03 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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




// Scala program of Object Casting
// Int to Float
case class Casting(a:Int)
 
// Creating object
object GfG
{
     
    // Main method
    def main(args:Array[String])
    {
         val a = 10
         
        // Casting value of a into float
        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




// Scala program of Object Casting
// Char to Int
case class Casting(c:Char)
 
// Creating object
object GfG
{
     
    // Main method
    def main(args:Array[String])
    {
         val c = 'c'
         
        // Casting value of c into Int
        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




// Scala program of Object Casting
// Float to Int
case class Casting(a:Float, b:Float)
 
// Creating object
object GfG
{
     
    // Main method
    def main(args:Array[String])
    {
         val a = 20.5
         val b = 10.2
         
        // Casting value of c into Int
        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.


Next Article
How to Create a JSON Object in Scala?
author
nidhi1352singh
Improve
Article Tags :
  • Scala
  • Scala
  • Scala-Data Type
  • Scala-OOPS

Similar Reads

  • Class and Object in Scala
    Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. Class A class is a user-defined blueprint or prototype from which objects are created. Or in other words, a class combines the fields and methods(member function which defines actions)
    5 min read
  • 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 methodThis perspective is required in ma
    4 min read
  • Inner class in Scala
    Inner class means defining a class into another. This feature enables the user to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code. In Scala, the concept of inner classes is different from Java. Like
    3 min read
  • How to Create a JSON Object in Scala?
    JSON(JavaScript Object Notation) plays an important role in web development and data transmission. In web applications, we frequently use JSON, a lightweight data transmission standard. Working with JSON data is made easy using Scala, a sophisticated programming language for the Java Virtual Machine
    2 min read
  • How to mock object in Scala?
    In software development, mocking is a technique used to isolate the unit under test by replacing external dependencies with simulated objects or "mocks". Mocking is particularly useful when working with objects that are difficult to set up or have side effects, such as databases, web services, or fi
    3 min read
  • Determine the class of a Scala object
    To determine the class of a Scala object we use getClass method. This method returns the Class details which is the parent Class of the instance. Below is the example to determine class of a Scala object. Calling method with argument - Example #1: // Scala program to determine the class of a Scala o
    2 min read
  • Scala | Case Class and Case Object
    Explanation of Case Class A Case Class is just like a regular class, which has a feature for modeling unchangeable data. It is also constructive in pattern matching. It has been defined with a modifier case, due to this case keyword, we can get some benefits to stop oneself from doing a sections of
    4 min read
  • HashSet In Scala
    HashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantic
    4 min read
  • ListSet in Scala
    A set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest elemen
    6 min read
  • Scala | Method Invocation
    Method Invocation is a technique that demonstrates different syntax in which we dynamically call methods of a class with an object. The naming conventions of Scala are same as of Java, that are:- There should not be any space between the invocation object/target and the dot(.) nor a space between th
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences