Scala: Case Classes

Micah Lewis
2 min readNov 20, 2020

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
b
}
def unapply(b: Book): String = s"${b.isbn}"
}
val frankenstein = new Book("978-0486282114")

This is how we would normally would define a class for a new book, say Frakenstein. Now take a look at the same code using the power of Scala’s case class

case class Book(isbn: String)val frankenstein = Book("978-0486282114")

Muuuuuuuuch easier. Take a look at the two bits of code and think about what the difference are. Below is a list of differences between case classes and regular classes in Scala

  • Case class do not need to have an apply and unapply method. They are created behind the scenes in its companion object.
  • 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 have some other handy built-in functions that you might find useful, for example .toString which, you probably guessed it, converts what you put before it into a string.
  • Case classes also can be used in equality statements for example, take a follow up to the code above:
message1 == message2 //returns true

Well, let’s keep this from dragging on, and wrap up here. Again if you spotted any mistakes, have any questions, or anything to add, please let me know in the comments below! Thanks for reading!

--

--