Careeroza
in, Range and Bitwise Operators
in and !in
Example
in checks whether a value is inside a range or a collection.
fun main() {
val hour = 14
println(hour in 9..21) // restaurant open?
val city = "Pune"
val serviceable = listOf("Pune", "Mumbai", "Delhi")
println(city in serviceable)
println("Goa" !in serviceable)
println('k' in 'a'..'z')
}Output
true true true true
Bitwise Operations
Example
Kotlin has no &, |, << symbols for integers. It uses named infix functions instead: and, or, xor, inv(), shl, shr, ushr.
fun main() {
val read = 0b001
val write = 0b010
val exec = 0b100
val perms = read or write
println(perms) // 3
println(perms and write != 0) // has write permission?
println(perms and exec != 0)
println(1 shl 4) // 16
println(64 shr 2) // 16
println(5 xor 3) // 6
}Output
3 true false 16 16 6
Note: Bitwise operations are used for flags, for example Android Intent flags and view gravity.
Operator Precedence
| Priority (high to low) | Operators |
|---|---|
| Postfix | x++, x--, ., ?., !! |
| Prefix | -x, ++x, ! |
| Multiplicative | *, /, % |
| Additive | +, - |
| Range | .., ..< |
| Infix functions | shl, and, until, to... |
| Elvis | ?: |
| Named checks | in, !in, is |
| Comparison | <, >, <=, >= |
| Equality | ==, !=, === |
| Logical | && then || |
| Assignment | =, +=... |
Tip: When in doubt, add parentheses. (a + b) * c is easier to read than relying on precedence.