Lesson contents

Kotlin — val, var, and integer arithmetic

In Kotlin, val creates a binding that cannot be reassigned and var permits reassignment. Integer division and remainder can split a price in cents into dollars and cents.

A simple example

Change a stored number

  1. Start with n starts at 2
  2. Do this Add 1 to n
  3. Result 3
After the assignment, reading the same variable gives its new value.
Lesson.kt
fun main() {
    var n = 2
    n++
    println(n)
}
Output
3
Advertisements

Calculate a receipt in cents

val binds a name once, while var allows reassignment. The total uses Int arithmetic, so dividing by 100 gives an integer. Locale.ROOT keeps the formatted example consistent across machines.

Notebooks: 3 × 125¢ = 375¢. Delivery: 50¢. Amount to pay: 425¢.
Check a stationery order

A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
fun main() {
    val priceCents = 125
    val quantity = 3
    val total = priceCents * quantity + 50
    println("%d.%02d".format(java.util.Locale.ROOT, total / 100, total % 100))
}
Output
4.25

Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.

Try it yourself

What happens if each item costs 101 cents?

Check your answer

Three items plus delivery cost 353 cents, so the output becomes 3.53.

Kotlin language documentation

Related tags

  • Kotlin
  • integers
  • variables
  • arithmetic