Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how do I get the *name* of an `object` (not an instance of a class)?

In Scala, I can declare an object like so:

class Thing

object Thingy extends Thing

How would I get "Thingy" (the name of the object) in Scala?

I've heard that Lift (the web framework for Scala) is capable of this.

like image 574
Scoobie Avatar asked Oct 21 '12 05:10

Scoobie


People also ask

What is the difference between a class and an object in Scala?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.

Can I have a class and object with same name in a Scala file?

An object with the same name as a class is called a companion object. Conversely, the class is the object's companion class. A companion class or object can access the private members of its companion. Use a companion object for methods and values which are not specific to instances of the companion class.

What is object keyword in Scala?

The object keyword creates a new singleton type, which is like a class that only has a single named instance. If you're familiar with Java, declaring an object in Scala is a lot like creating a new instance of an anonymous class.

What is the type of an object in Scala?

Scala is more object-oriented than Java because in Scala, we cannot have static members. Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword object instead of class keyword.


2 Answers

If you declare it as a case object rather than just an object then it'll automatically extend the Product trait and you can call the productPrefix method to get the object's name:

scala> case object Thingy
defined module Thingy

scala> Thingy.productPrefix
res4: java.lang.String = Thingy
like image 122
DaoWen Avatar answered Oct 17 '22 22:10

DaoWen


Just get the class object and then its name.

scala> Thingy.getClass.getName
res1: java.lang.String = Thingy$

All that's left is to remove the $.

EDIT:

To remove names of enclosing objects and the tailing $ it is sufficient to do

res1.split("\\$").last
like image 24
Kim Stebel Avatar answered Oct 17 '22 20:10

Kim Stebel