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 check String is null in Scala?
Next article icon

How to Check Datatype in Scala?

Last Updated : 07 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn to check data types in Scala. Data types in Scala represent the type of values that variables can hold, aiding in type safety and program correctness.

Table of Content

  • Checking Datatype in Scala
    • Approach 1: Use Pattern Matching in Scala
    • Approach 2: Use the getClass Method in Scala
    • Approach 3: Use Manifest in Scala
    • Approach 4: Use Type Checking (isInstanceOf) in Scala

Checking Datatype in Scala

Below are the possible approaches to check datatype in Scala.

Approach 1: Use Pattern Matching in Scala

  1. In this approach, we are using Pattern Matching in Scala to dynamically check the type of an object and return a corresponding string representing the detected data type.
  2. The approach1Fn method matches the object against different patterns (String, Int, List[_]), providing a flexible way to handle different data types in a concise and readable manner.

In the below example, Pattern Matching is used to check the datatype in Scala.

Scala
object GFG {   def main(args: Array[String]): Unit = {     val str: Any = "Hello"     val num: Any = 42     val lst: Any = List(1, 2, 3)     println(approach1Fn(str))      println(approach1Fn(num))      println(approach1Fn(lst))   }   def approach1Fn(obj: Any): String = obj match {     case _: String => "String"     case _: Int => "Int"     case _: List[_] => "List[Int]"     case _ => "Unknown"   } } 

Output:

1

Approach 2: Use the getClass Method in Scala

  1. In this approach, we use the getClass method in Scala to retrieve the runtime class of an object as a string.
  2. The approach2Fn method takes any object (Any) as input and returns the string representation of its runtime class.

In the below example, the getClass Method is used to check the datatype in Scala.

Scala
object GFG {   def main(args: Array[String]): Unit = {     val str: Any = "Hello"     val num: Any = 42     val lst: Any = List(1, 2, 3)      println(approach2Fn(str))      println(approach2Fn(num))      println(approach2Fn(lst))   }   def approach2Fn(obj: Any): String = obj.getClass.toString } 

Output:

2

Approach 3: Use Manifest in Scala

  1. In this approach, we are using Manifest in Scala to obtain type information at runtime.
  2. The approach3Fn method takes a type parameter T with a Manifest context-bounded.
  3. It uses manifest[T].toString to get the string representation of the type T.

In the below example, Manifest is used to check the datatype in Scala.

Scala
object GFG {   def main(args: Array[String]): Unit = {     val str: Any = "Hello"     val num: Any = 42     val lst: Any = List(1, 2, 3)     println(approach3Fn[Int](str))     println(approach3Fn[Int](num))      println(approach3Fn[List[Int]](lst))   }   def approach3Fn[T: Manifest](obj: Any): String = manifest[T].toString } 

Output:

3

Approach 4: Use Type Checking (isInstanceOf) in Scala

  1. In this approach, we are using Type Checking (isInstanceOf) in Scala to determine the type of an object at runtime.
  2. The approach4Fn method takes an Any object as input and checks its type using isInstanceOf.
  3. It returns a string representing the detected data type ("String", "Int", "List[Int]", or "Unknown").

In the below example, Type Checking (isInstanceOf) is used to check the datatype in Scala.

Scala
object GFG {   def main(args: Array[String]): Unit = {     val str: Any = "Hello"     val num: Any = 42     val lst: Any = List(1, 2, 3)     println(approach4Fn(str))     println(approach4Fn(num))     println(approach4Fn(lst))   }   def approach4Fn(obj: Any): String = {     if (obj.isInstanceOf[String]) "String"     else if (obj.isInstanceOf[Int]) "Int"     else if (obj.isInstanceOf[List[_]]) "List[Int]"     else "Unknown"   } } 

Output:

4


Next Article
How to check String is null in Scala?

G

gauravgandal
Improve
Article Tags :
  • Scala

Similar Reads

  • How to check dataframe size in Scala?
    In this article, we will learn how to check dataframe size in Scala. To check the size of a DataFrame in Scala, you can use the count() function, which returns the number of rows in the DataFrame. Here's how you can do it: Syntax: val size = dataframe.count() Example #1: [GFGTABS] Scala import org.a
    2 min read
  • How to Check Data Type in R?
    R programming has data types that play a very significant role in determining how data is documented, modified, and analyzed. Knowing the data type of an object is an essential part of most data analysis and programming. The current article delivers a step-by-step guide that will familiarize you wit
    4 min read
  • How to Check the Schema of DataFrame in Scala?
    With DataFrames in Apache Spark using Scala, you could check the schema of a DataFrame and get to know its structure with column types. The schema contains data types and names of columns that are available in a DataFrame. Apache Spark is a powerful distributed computing framework used for processin
    3 min read
  • How to print dataframe in Scala?
    Scala stands for scalable language. It was developed in 2003 by Martin Odersky. It is an object-oriented language that provides support for functional programming approach as well. Everything in scala is an object e.g. - values like 1,2 can invoke functions like toString(). Scala is a statically typ
    4 min read
  • How to check String is null in Scala?
    In this article, we will learn how to check if a string is null in Scala. In Scala, you can check if a string is null using the following methods: Table of Content 1. Using the == operator:2. Using the eq method (recommended):3. Using Pattern Matching:1. Using the == operator:[GFGTABS] Scala object
    2 min read
  • Data Types in Scala
    A data type is a categorization of data which tells the compiler that which type of value a variable has. For example, if a variable has an int data type, then it holds numeric value. In Scala, the data types are similar to Java in terms of length and storage. In Scala, data types are treated same o
    3 min read
  • Scala Char getType() method with example
    The getType() method is utilized to return a value of type integer representing the character’s general category. Method Definition: def getType: Int Return Type: It returns an Integer. Example: 1# // Scala program of getType() // method // Creating object object GfG { // Main method def main(args:A
    1 min read
  • How to Overcome Type Erasure in Scala?
    Type erasure may provide challenges in Scala, particularly when dealing with generics. Type tags and manifests are a means to prevent type erasure. By preserving type information during runtime, these approaches let you operate with genuine types as opposed to erased types. Table of Content What is
    3 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
  • Scala Char toInt() method with example
    The toInt() method is utilized to convert a stated character into an integer or its ASCII value of type Int. Method Definition: def toInt: Int Return Type: It returns Integer or ASCII value of the corresponding character of type Int. Example: 1# // Scala program of toInt() // method // Creating obje
    1 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