How the get the classOf for a scala object type
Asked Answered
R

4

71

I wonder how to get a class object for an object type in Scala. Ok, that is a mouth full because of the double meaning for object. So here an example which will fail:

object Main
{
   private [this] val TAG = classOf [Main].getName;
} // Main

If Main was class it works perfectly. Any ideas?

Radices answered 9/3, 2012 at 14:21 Comment(0)
D
99
scala> Main.getClass
res1: java.lang.Class[_] = class Main$
Drogue answered 9/3, 2012 at 14:26 Comment(4)
Yes. I see, now it becomes all clear. objects have exactly one instance and therefore you call getClass. Thanks.Radices
@Radices Actually, I'd say that's incorrect. objects don't have instances at all, because they aren't types; they are the only instances of (compiler-generated) classes, and that's why you can call getClass.Drogue
Is their a Way to do this as a compile time Constant so that it can be used for a Java Annotation Attribute of type Class ?Cerussite
@MarkusKnecht I don't know one; you may want to ask this as a separate question.Drogue
S
20

The reason why classOf[Main] doesn't work is because Main is not a type.

Classes and traits define types, objects do not.

Squelch answered 9/3, 2012 at 15:9 Comment(0)
S
10

Since Main is an object, for your example to work, simply replace your assignment line with;

private [this] val TAG = this.getClass.getName;
Szczecin answered 9/3, 2012 at 14:34 Comment(0)
C
0

It is possible to refer an object type. e.g:

classOf[Main.type]
Clomp answered 19/12, 2023 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.