Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Is it a class instance?

Tags:

scala

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?

like image 467
barbara Avatar asked Mar 17 '23 18:03

barbara


1 Answers

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
like image 76
dhg Avatar answered Mar 21 '23 20:03

dhg