How can I easily get the class name of a Scala class?

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 ?

+44
scala class classname
Apr 16 '10 at 10:10
source share
5 answers
 def name = this.getClass.getName 

Or, if you want only a name without a package:

 def name = this.getClass.getSimpleName 

See the java.lang.Class documentation for more details.

+64
Apr 16 2018-10-16T00:
source share

You can use the productPrefix property 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 

NB If you go to scala 2.8 extending the case class are deprecated and you should not forget the left and right parents ()

+17
Apr 16 '10 at 23:02
source share
 def name = this.getClass.getName 
+11
Apr 16 2018-10-10T00:
source share
 class Example { private def className[A](a: A)(implicit m: Manifest[A]) = m.toString override def toString = className(this) } 
+11
Apr 16 '10 at
source share

Here is a Scala function that generates a human-readable string from any type, recursive by parameter types:

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] } 
+5
Jan 23 '15 at 2:37
source share



All Articles