When you instantiate a class with the new
operator, you get a new instance of the class. The new instance is an object.
You can declare a singleton object with the object
keyword. Saying that it is instantiated at compile time doesn't really mean anything. Objects only exist while the program runs, not before that time (such as when you are compiling the program). An object
is instantiated the first time it is used.
Is 4 a case class of Int? Is 5.07 a case class of Double?
No. 4 and 5.07 are just instances of the classes Int
and Double
. In Scala they behave in the same way as objects, but behind the scenes 4 and 5.07 are not really objects. To understand this, you have to know about the standard Scala class hierarchy.
At the top of the hierarchy is the type Any
. Everything extends Any
. Any
has two direct subtypes: AnyVal
and AnyRef
.
AnyVal
is the supertype of all value types. Value types are the types that map to JVM primitive types (for example: Int
-> int
, Double
-> double
etc.).
AnyRef
is the supertype of all reference types ("regular" objects).
At runtime, everything that extends AnyRef
is an object behind the scenes, and everything that extends AnyVal
isn't really an object; it maps to a primitive type.
Case classes are just a kind of syntactic sugar. A case class is exactly the same as a normal class, except that the compiler adds some methods automatically for you (which makes them suitable for pattern matching, for example).