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 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.
Recommended Posts:
- Class and Object in Scala
- Scala | Case Class and Case Object
- Object Casting in Scala
- Object Equality in Scala
- Scala | Stateful Object
- Inner class in Scala
- Extending a Class in Scala
- Call a method on a Super Class in Scala
- Calling A Super Class Constructor in Scala
- Scala Tutorial – Learn Scala with Step By Step Guide
- Scala Map
- Set in Scala | Set-1
- Scala | Either
- Set in Scala | Set-2
- Scala short &(x: Int): Int
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

