Case classes in Scala
A Lighthouse record with generated printing and equality, taken apart by a match.
// a case class is an immutable record whose fields are public vals
case class Lighthouse(name: String, heightM: Int, flashSec: Int)
// no new keyword is needed to build one
val portland: Lighthouse = Lighthouse("Portland", 41, 5)
// toString is generated, printing the class name and the fields
val printed: String = portland.toString
// equality compares the fields, so two separate builds are equal
val twin: Lighthouse = Lighthouse("Portland", 41, 5)
val sameLight: Boolean = portland == twin
// match takes the value apart by position, binding each field to
// a name; a literal in one slot only matches that exact value
def describe(light: Lighthouse): String = light match
case Lighthouse(name, height, 5) => s"$name, ${height}m, quick"
case Lighthouse(name, _, secs) => s"$name every ${secs}s"
val summary: String = describe(portland)
How it works
case class Lighthouse(name: String, heightM: Int, flashSec: Int)declares the record, andLighthouse("Portland", 41, 5)builds one with no new keyword.portland.toStringis generated from the fields, andportland == twincompares field by field, so two separately built lighthouses come out equal.case Lighthouse(name, height, 5)binds fields by position and matches only when the third is that literal, leavingcase Lighthouse(name, _, secs)for the rest.
Keywords and builtins used here
BooleanIntLighthouseStringcaseclassdefdescribematchval
The run, in numbers
- Lines
- 20
- Characters to type
- 847
- Tokens
- 123
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 98 seconds.
Step 1 of 3 in Case classes & enums, step 16 of 27 in Language basics.