Groovy — Final variables and fixed values
A final variable can be assigned only once. When the variable holds a mutable object, final protects the binding while the object can still change.
A simple example
Use a fixed value
- Start with Unit is 3
- Do this Multiply by 2
- Result 6
final int 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. The fixed interval is an integer here. A final list, in contrast, could still have elements added unless the list itself prevents mutation.
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 Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
final int baseMinutes = 15
final int slotMinutes = 2 * baseMinutes
int bookedSlots = 3
println((bookedSlots * slotMinutes).toString() + ' 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.