Sorry, considering the other blog posts I did on apply and unapply as well as companion objects, this one regarding case classes seems a bit out of order. Nevertheless, we should talk about case classes which are special to Scala. Case classes bring class instantiation [creation] and definition into the modern world. Consider the following code:

class Book(isbn: String) {
def apply(isbn: String) = {
val b = new Book
b.isbn = isbn
def unapply(b: Book): String = s"${b.isbn}"
val frankenstein = new Book("978-0486282114")
case class Book(isbn: String)val frankenstein = Book("978-0486282114")
  • Because of this, the case class does not need the “new” keyword when instantiating [creating] a new instance of the class. [As of writing, I don’t know why this is. If you know, please help me out and let me know in the comments below]
  • All of the values created defined within a case class are public val and cannot be changed. If you want to change the value of a value in a class, the case classes have a very handy .copy method for handling this:
case class Message(sender: String, recipient: String)

val message1 = Message("micah", "artem")
val message2 = message1.copy //creates a shallow copy of message1
val message3 = message1.copy(sender = "richard")
  • Case classes also can be used in equality statements for example, take a follow up to the code above:
message1 == message2 //returns true