简体   繁体   中英

What is the type of a companion object in Scala?

For example, I have:

class AClass {

}
object AClass{

}

.....

println(AClass.getClass.toString)
println((new AClass).getClass.toString)
println(AClass.toString)
println((new AClass).toString)

When I tried to print out the types of the class and the companion object,I got:

class tmp.AClass$
class tmp.AClass
tmp.AClass$@44a664f2
tmp.AClass@7f9fcf7f

I think the type of an instance of the class AClass is AClass.

What is the type of the companion object AClass? What is the dollar symbol's meaning in AClass$ ?

What is the type of the class AClass? Can I use the class AClass directly without make an instance of it?

The dollar sign is a valid part of a class name on the JVM. You will see it commonly used in generated classes. So AClass$ is just a normal class name with nothing special about it.

Of course that's only it's run-time type that it gets compiled to. Within scala code, the type of the companion to AClass is AClass.type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM