Determine the class of a Scala object
Last Updated :
02 Aug, 2019
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:
object Geeks
{
def printClass(num : Int*)
{
println( "class: " + num.getClass)
}
def main(args : Array[String])
{
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:
object Geeks
{
def printClass(num : Int*)
{
println( "class: " + num.getClass)
}
def main(args : Array[String])
{
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:
sealed trait Person
class Boy extends Person
class Girl extends Person
object Person
{
def getPerson(s : String) : Person =
if (s == "Boy" ) new Boy else new Girl
}
object ObjectCastingTest extends App
{
val person = Person.getPerson( "Boy" )
println( "person: " + person.getClass)
println( "person: " + person.getClass.getName)
println( "person: " + person.getClass.getSimpleName)
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
Share your thoughts in the comments
Please Login to comment...