Lesson contents

Kotlin — Read-only val and compile-time const val

val prevents reassignment of a binding. const val declares a compile-time constant for eligible primitive or String values in permitted declaration locations.

A simple example

Use a fixed value

  1. Start with Unit is 3
  2. Do this Multiply by 2
  3. Result 6
Give 3 a name and reuse that name in the multiplication.
Lesson.kt
const val UNIT = 3
fun main() {
    println(2 * UNIT)
}
Output
6
Advertisements

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. Put these constants at the top level so the compiler can use them in other constant expressions. A local val can also be initialized from a runtime calculation.

Length of a slot: 30 minutes. Rehearsal: 3 slots. Time reserved: 90 minutes.
Reserve a rehearsal room

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 Kotlin 2.2 on the JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
const val BASE_MINUTES = 15
const val SLOT_MINUTES = 2 * BASE_MINUTES

fun main() {
    val bookedSlots = 3
    val duration = bookedSlots * SLOT_MINUTES
    println("$duration minutes")
}
Output
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.

Kotlin language documentation

Related tags

  • Kotlin
  • constants
  • bindings
  • configuration