Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 341
pr1001 Avatar asked Apr 16 '10 22:04

pr1001


People also ask

What methods get generated when we declare a case class in scala?

An unapply method is generated, which lets you use case classes in more ways in match expressions. A copy method is generated in the class.

How do I get a classname class?

You can use: Class c = Class. forName("com.

What is getClass in scala?

The getClass() method is utilized to return the class of the given number. Method Definition: (Number).getClass. Return Type: It returns the class of the given number. Example #1: // Scala program of Float getClass()

For which kind of data should you use a case class in scala?

A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.


1 Answers

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.

like image 169
Esko Luontola Avatar answered Sep 19 '22 22:09

Esko Luontola