简体   繁体   中英

What's behind Scala case classes?

I'm quite new to Scala but I have already used case classes. I understood what are main differences between a regular class and a case class as summarized here .

I do not even think to get rid of case classes, but I would like to know what's the code needed to transform for example, this:

class Tweet(val user: String, val text: String) {
  override def toString: String =
    "User: " + user + "\n" +
    "Text: " + text + "]"
}

into a full case "compatible" class. I mean, I would like to code the same "behavior" of a case class but without using case keyword. Is this possible or does the compiler do something that I cannot get through code (excluding optimizations)?

Once again to make clear what I'm asking, I will always use case keyword when I need a case class, but once in life time, I would like to know what the Scala compiler (in generic sense) does for me, expressed in code terms.

edit: An additional doubt: will the compiler mark somehow differently my hand coded class from an standard case class so that I can observe a different behavior in execution?

You can have a look at chapter 5.3.2 "Case Classes" in the scala spec.

If I summarize correctly, the following is auto-generated:

  • accessors are generated for the class elements
  • an extractor object with apply/unapply is automatically generated
  • a method copy is automatically added
  • methods equals, hashCode, toString are overriden

You could compare the scala source and the generated java bytecode to be sure.

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