How can I easily get a Scala case class's name?

pr1001 picture pr1001 · Apr 17, 2010 · Viewed 55.7k times · Source

Given:

case class FirstCC {
  def name: String = ... // something that will give "FirstCC"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()

How can I get "FirstCC" from one.name and "SecondCC" from two.name?

Answer

Esko Luontola picture Esko Luontola · Apr 17, 2010
def name = this.getClass.getName

Or if you want only the name without the package:

def name = this.getClass.getSimpleName

See the documentation of java.lang.Class for more information.