Open In App

Determine the class of a Scala object

Last Updated : 02 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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 object
  
// Creating object 
object Geeks
    // Using getClass method
    def printClass(num: Int*) 
    {
        println("class: " + num.getClass)
    }
      
    // Main method 
    def main(args: Array[String]) 
    
        // Calling parameter with parameter
        printClass(4, 2)
    


Output:

class: class scala.collection.mutable.WrappedArray$ofInt

In above example, Calling the printClass method with parameter demonstrates the class Scala.

Calling method without argument –

Example #2:




// Scala program to determine the class of a Scala object
  
// Creating object 
object Geeks 
    // Using getClass method
    def printClass(num: Int*) 
    {
        println("class: " + num.getClass)
    }
      
    // Main method 
    def main(args: Array[String]) 
    
        // Calling method without parameter
        printClass()
    


Output:

class: class scala.collection.immutable.Nil$

In above example, Calling the printClass method without parameter demonstrates the class Scala.

With additional get* methods –

Example #3:




// Scala program to show how 
// the additional get* methods work
  
sealed trait Person
class Boy extends Person
class Girl extends Person
  
// Creating object
object Person 
{
    // factory method
    def getPerson(s: String): Person = 
        if (s == "Boy") new Boy else new Girl
}
  
object ObjectCastingTest extends App 
{
  
    val person = Person.getPerson("Boy")
      
    // class object_casting.Boy
    println("person: " + person.getClass)
      
    // object_casting.Boy
    println("person: " + person.getClass.getName)  
      
    // Boy
    println("person: " + person.getClass.getSimpleName)  
      
    // object_casting.Boy
    println("person: " + person.getClass.getCanonicalName)  
  
}


Output:

person: class Boy
person: Boy
person: Boy
person: Boy

Above code show how the additional get* methods getName, getSimpleName, and getCanonicalName work.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads