Scala — Stable values with val and final val
A Scala val binds a value once. A final val member can also prevent overriding, and eligible constant definitions can be used as compile-time constants in Scala 2.13.
A simple example
Use a fixed value
- Start with Unit is 3
- Do this Multiply by 2
- Result 6
object Lesson extends App {
val unit = 3
println(2 * unit)
}
6
Name a fixed scheduling interval
Express a 30-minute slot in terms of a 15-minute base interval. Keep the slot count separate so different bookings can reuse the same rule. Keep the fixed interval in a named object. A val referring to mutable data still permits operations on that data, so binding stability and object immutability are distinct properties.
The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.
Run the example
Use Scala 2.13. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
object Schedule {
final val BaseMinutes = 15
final val SlotMinutes = 2 * BaseMinutes
}
def main(args: Array[String]): Unit = {
val bookedSlots = 3
val duration = bookedSlots * Schedule.SlotMinutes
println(s"$duration minutes")
}
}
90 minutes
Two base intervals make each slot 30 minutes. A booking of three slots lasts 90 minutes.
Try it yourself
If the base interval changes to 10 minutes, how long is the same three-slot booking?
Check your answer
Each slot now lasts 20 minutes, so the booking lasts 60 minutes.