If I run this code (see it below) I get CaseClass
as printed message.
case class CaseClass(var name: String)
object Main extends App {
val obj = CaseClass
println(obj)
}
But what does it mean? I mean is CaseClass
similar to Java's CaseClass.class
?
When you define a case class
it actually defines both a class
AND an object
, both with the same name. When you say val obj = CaseClass
, you are actually assigning the object
, a singleton object, to obj
.
It's kind of like:
class NonCaseClass(var name: String) { // the actual class
override def toString = "the class version"
}
object NonCaseClass { // singleton companion object
override def toString = "the object version"
}
val obj = NonCaseClass // this assigns the companion object to a variable
println(obj)
// the object version
This is different from instantiating an instance of the class CaseClass
:
val obj2 = new NonCaseClass("x")
println(obj2)
// the class version
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