More Operators
In the preceding chapter, we saw mathematical expressions and various operators, such as +
and -
. Those operators can work on literal values as we saw. Not surprisingly, they can also work with variables:
val count = 5
val more = count + 2
println(more)
As you might expect, this prints 7
as the output.
However, now that we have variables, we have more operators that we can use!
Increments and Decrements
Akin to many other programming languages, we can use ++
and --
operators to increment and decrement a variable by 1:
fun main() {
var postIncrement = 5
println("postIncrement ${postIncrement} ${postIncrement++} ${postIncrement}")
var preIncrement = 5
println("preIncrement ${preIncrement} ${++preIncrement} ${preIncrement}")
var postDecrement = 5
println("postDecrement ${postDecrement} ${postDecrement--} ${postDecrement}")
var preDecrement = 5
println("preDecrement ${preDecrement} ${--preDecrement} ${preDecrement}")
}
Here, we use string interpolation with println()
to show the value of a variable before, “during”, and after an increment or decrement operation.
The results are:
postIncrement 5 5 6
preIncrement 5 6 6
postDecrement 5 5 4
preDecrement 5 4 4
So:
- Post-increment (
variable++
) increments the variable after the use - Pre-increment (
++variable
) increments the variable before the use - Post-decrement (
variable--
) decrements the variable after the use - Pre-decrement (
--variable
) decrements the variable before the use
Of course, these only work with var
, as the value of a val
is “immutable” and cannot be changed.
Augmented Assignments
Similarly, there are also operators that evaluate a mathematical expression and assign it to the var
in one shot, such as +=
:
var count = 5
count += 2
println(count)
This prints 7
, showing that count
had its value incremented by 2. This is the equivalent of:
var count = 5
count = count + 2
println(count)
There are -=
, *=
, /=
, and %=
operators as well, combining those mathematical operators with assigments.
Unary Operators
Most programming languages offer !
(or some equivalent) as a “unary operator”, which inverts the value of a Boolean
. Kotlin has that, along with a -
negation operator that inverts the sign of a number:
val thisIsTrue = true
println(!thisIsTrue)
val whySoNegative = -5
println(-whySoNegative)
As you might expect, this prints:
false
5
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.