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.
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With