Arithmetic in Kotlin looks exactly like what you learned in math class. Plus, minus, times, divide — it's all here, plus a few extras.
The basics
fun main() {
val a = 10
val b = 3
println("a + b = ${a + b}") // addition
println("a - b = ${a - b}") // subtraction
println("a * b = ${a * b}") // multiplication
println("a / b = ${a / b}") // division (integer, result is 3)
println("a % b = ${a % b}") // modulus (remainder, result is 1)
}
Notice that 10 / 3 gives you 3, not 3.333. That's because both numbers are integers, so Kotlin does integer division. Use doubles if you want decimals.
Increment and decrement
++ adds 1, -- subtracts 1. Use them before or after a variable name.
fun main() {
var counter = 0
counter++ // now 1
println(counter)
counter-- // back to 0
println(counter)
println(++counter) // prints 1 (increments first, then prints)
println(counter++) // prints 1 (prints first, then increments)
println(counter) // now 2
}
Try it Yourself →