1

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?

Community
  • 1
  • 1
giampaolo
  • 6,906
  • 5
  • 45
  • 73
  • 1
    The Scala compiler doesn't differentiate the two. Case classes are just normal classes but the compiler auto-generates a lot of things that go with them and so they behave differently. You may consider a simpler answer to the problem you are facing. – Dante Romero Nov 26 '13 at 07:05

1 Answers1

4

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.

ewernli
  • 38,045
  • 5
  • 92
  • 123
  • If feel like you could create a regular class that is technically like a case class, but the type system wouldn't know it's a case class, so maybe it could still lead to differences in use (maybe with pattern matching). But I don't knwo scala enough to be sure about this. – ewernli Nov 03 '13 at 19:36
  • @giampaolo you changed your question to ask about the runtime, while ewrnli mentioned the type system, which is a compile time thing. The only difference I can think of is that the compiler will complain if you try to extend a case class with another case class (used to be possible, but it caused problems). How it would know that the class it's extending is a case class if you're importing it from elsewhere, I'm not sure. – Luigi Plinge Nov 03 '13 at 22:03
  • @LuigiPlinge: ok, I changed last sentence. I hope is more clear now. – giampaolo Nov 04 '13 at 06:46