Scala — Modeling values with case classes
A Scala case class groups the values in a record and supplies structural equality. A method can derive the subtotal from the quantity and unit price.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
object Lesson extends App {
case class Point(x: Int)
println(Point(2).x)
}
2
Represent an invoice line
A case class supplies immutable constructor fields and structural equality. The subtotal method has no parameter list because it computes a value from those fields.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
case class LineItem(units: Int, cents: Int) {
def subtotal: Int = units * cents
}
def main(args: Array[String]): Unit = {
val line = LineItem(units = 3, cents = 125)
println(line.subtotal)
}
}
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.