Kotlin Map.mapValues
Calculate a new price for each item on the takeaway menu.
A simple example
Map.mapValues
- Start with A = 1, B = 2
- Do this Add 1 to each value
- Result A = 2, B = 3
Syntax
prices.mapValues { it.value + 1 }
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarAdd a packing charge to each listed price
A café starts packing takeaway orders in reusable boxes. The manager adds one unit to each listed price and checks the new soup price before publishing the board.
Result5
fun main() {
val prices = mapOf("Soup" to 4, "Salad" to 6)
val revised = prices.mapValues { it.value + 1 }
println(revised.getValue("Soup"))
}
5
Soup increases from four to five after the packing charge.
Advertisements
Reprint stationery prices
A school shop increases every price by two credits. Every price gets the same increase. Find the revised value for the first item.
GivenPen 7 · increase 2
Worked result9
Revise rental rates
A studio adds a three-credit cleaning fee to every rental. Every price gets the same increase. Find the revised value for the first item.
GivenStand 12 · increase 3
Worked result15
What to watch for
mapValues returns a new map. Keep its result when publishing the revised menu.