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

ScalaClassClassname

Scala Problem Overview


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?

Scala Solutions


Solution 1 - Scala

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.

Solution 2 - Scala

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 ()

Solution 3 - Scala

class Example {
  private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
  override def toString = className(this)
}

Solution 4 - Scala

def name = this.getClass.getName

Solution 5 - Scala

Here is a Scala function that generates a human-readable string from any type, recursing on type parameters:

https://gist.github.com/erikerlandson/78d8c33419055b98d701

import scala.reflect.runtime.universe._
 
object TypeString {
 
  // return a human-readable type string for type argument 'T'
  // typeString[Int] returns "Int"
  def typeString[T :TypeTag]: String = {
    def work(t: Type): String = {
      t match { case TypeRef(pre, sym, args) =>
        val ss = sym.toString.stripPrefix("trait ").stripPrefix("class ").stripPrefix("type ")
        val as = args.map(work)
        if (ss.startsWith("Function")) {
          val arity = args.length - 1
          "(" + (as.take(arity).mkString(",")) + ")" + "=>" + as.drop(arity).head
        } else {
          if (args.length <= 0) ss else (ss + "[" + as.mkString(",") + "]")
        }
      }
    }
    work(typeOf[T])
  }
 
  // get the type string of an argument:
  // typeString(2) returns "Int"
  def typeString[T :TypeTag](x: T): String = typeString[T]
}

Solution 6 - Scala

def name = getClass.getSimpleName.split('$').head

This will remove the $1 appearing at the end on some classes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpr1001View Question on Stackoverflow
Solution 1 - ScalaEsko LuontolaView Answer on Stackoverflow
Solution 2 - ScalaPatrickView Answer on Stackoverflow
Solution 3 - ScalaDaniel C. SobralView Answer on Stackoverflow
Solution 4 - ScalaRex KerrView Answer on Stackoverflow
Solution 5 - ScalaejeView Answer on Stackoverflow
Solution 6 - ScalaJavier MontónView Answer on Stackoverflow