views:

126

answers:

4

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?

+2  A: 
def name = this.getClass.getName
Rex Kerr
Thanks, I didn't know about `getName`. Much better than `toString`.
pr1001
+3  A: 
class Example {
  private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
  override def toString = className(this)
}
Daniel
What is the benefit of this (2.8-only) approach over `this.getClass.getName`?
pr1001
@pr1001 It will preserve type parameters if you have them.
Daniel
+3  A: 
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.

Esko Luontola
+2  A: 

You can use the property productPrefix of the case class:

case class FirstCC {
  def name = productPrefix
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()

one.name
two.name

N.B. If you pass to scala 2.8 extending a case class have been deprecated, and you have to not forget the left and right parent ()

Patrick
Thanks, I didn't know about the productPrefix property.
pr1001