I read this statement:
By using User.getClass, you are referring to the class companion object that Scala by default creates for the case class, and not the case class itself.
To get the class object of the case class, use classOf[User].
Where could I come unstuck by using the class of the companion object? I would have thought - showing my ignorance here - they would be the same.
Java has something called static methods
it is like a method but not attached to an instance
These static methods are used for storing globals (not recommended), or stateless functions not depending on object - like e.g. factories and other utilities. These methods can access private/protected members of the instances, and instances can access private/protected static methods - so you can limit visibility as if they were inside the object, even though they aren't (Java's reflection treats their methods as if they had
nullasthis).In Scala we didn't want to have the distinction for static and non-static methods so we decided to do the following:
objectfrom otherobjectsThat's how we arrived at companion object.
getClassis method that you can call on any object - sincefooandFoohave different classes they would return different values forgetClass.Any value can describe their type with
.typesofoo.typewould be the type offoovariable (Foo) andFoo.typewould be the type ofFooobject which is companion ofFooclass (and would be calledFoo$in bytecode).From the reason why companion object exist, it follows that Foo and its companion does not have the same (instance) methods, so they cannot have the same interface, and so they cannot be of the same type.
When it comes to
case classes they just automatically create a companion object (if it doesn't exist) and generate some methods inside it based on their constructor: e.g.apply,unapply.