ScalaSchool

#Case Classes

Case Classes are regular classes with some “Free Stuff”


Description

case class Person(name: String, age: Int)

Classes defined with the case modifier are called case classes. Using the modifier cases the Scala compiler add some syntactic sugar to the class.

case class Person(name: String, age: Int)
val p = Person("ryan", 21)  //instead of val p = new Person("ryan", 21)

p match {
  case Person(name, age) =>  println(s"$name and $age extracted!")
}
case class Person(name: String, age: Int)
val p = Person("ryan", 21)
println(p.name) //is allowed

Since == in Scala always delegates to equals, this means that elements co case classes are always compared structurally:

case class Person(name: String, age: Int)
val p1 = Person("bob", 19)
val p2 = Person("bob", 19)
val p3 = p1.copy()

// Here p1 == p2 == p3 is true

Companion Class

A class that shares the same name with a singleton object defined in the same source file. The class is the singleton object’s companion class

Companion Object

A singleton object that shares the same name with a class defined in the same source file. Companion objects and classes have access to each other’s private members. In addition, any implicit conversions defined in the companion object will be in scope anywhere the class is used.

Case Classes & Companion Objects

Case classes have automatically generated companion objects

Class Classes