Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Operators and Bitwise Operations

Kotlin Operators and Bitwise Operations

Operators are symbols used to operate on data, such as addition +, comparison >, and logical AND &&。

Kotlin's arithmetic, assignment, comparison, and logical operators are basically the same as Java's, but bitwise operations have no symbols and instead use named functions.

This article also introduces range operators .. and ..<, which are very common syntactic sugar in Kotlin.


Arithmetic operators

Kotlin supports five binary arithmetic operators: addition, subtraction, multiplication, division, and remainder, plus unary plus/minus and increment/decrement.

One thing to note especially is integer division: when two integers are divided, the result is still an integer and the fractional part is simply discarded.

Example

fun main

(

)

{

    println

(

7

3

)

     

// 10

    println

(

7

3

)

     

// 4

    println

(

7

3

)

     

// 21

    println

(

7

/

3

)

     

// 2, integer division truncates the fractional part

    println

(

7

%

3

)

     

// 1, remainder

    println

(

7.0

/

3

)

   

// 2.3333333333333335, if one operand is floating-point the result is floating-point

    println

(

7

%

3

)

   

// -1, the sign of the remainder matches the dividend

   

// Integer division by zero throws an exception

   

// println(1 / 0) // throws ArithmeticException: / by zero

   

// Floating-point division by zero does not throw an exception

    println

(

1.0

/

0.0

)

 

// Infinity

    println

(

0.0

/

0.0

)

 

// NaN

   

// Unary operators

    println

(

5

)

       

// -5

    println

(

5

)

       

// 5

   

// Increment and decrement

    var i

=

1

    println

(

i

++

)

       

// 1, take the value first then add 1

    println

(

i

)

         

// 2

    println

(

++

i

)

       

// 3, add 1 first then take the value

    println

(

i

--

)

       

// 3

    println

(

i

)

         

// 2

}



10

4

21

2

1

2.3333333333333335

-1

Infinity

NaN

-5

5

1

2

3

3

2

Note:Kotlin has no exponentiation operator, don't write 2 ** 10. For integer powers use 1 shl 10, for floating-point powers use kotlin.math.pow。

Integer division's truncation behavior is error-prone; for example, when calculating percentages you should convert to floating-point first.

Example

fun main

(

)

{

    val done

=

3

    val total

=

4

   

// Two Ints divided, the result is truncated to 0

    println

(

done

/

total

)

                   

// 0

   

// Convert to Double first, then divide

    println

(

done.

toDouble

(

)

/

total

)

       

// 0.75

   

// Or scale up with multiplication first

    println

(

done

100

/

total

)

             

// 75

}



0

0.75

75


Assignment and compound assignment

Kotlin's assignment operator is =, plus five compound assignment operators that combine an operation with assignment.

operator Equivalent form Description
+= a = a + b Add then assign
-= a = a - b Subtract then assign
*= a = a * b Multiply then assign
/= a = a / b Divide then assign
%= a = a % b Remainder then assign

Example

fun main

(

)

{

    var a

=

10

    a

+=

5

     

// Equivalent to a = a + 5

    println

(

a

)

 

// 15

    a

-=

3

    println

(

a

)

 

// 12

    a

*=

2

    println

(

a

)

 

// 24

    a

/=

5

    println

(

a

)

 

// 4

    a

%=

3

    println

(

a

)

 

// 1

}



15

12

24

4

1

Note:In Kotlin, assignment is not an expression,a = b it has no return value. So while ((line = read()) != null) this Java-style construct won't compile in Kotlin; you must split it into two steps. Bitwise operations also have no corresponding compound assignment; there is no shl=, you can only write a = a shl 2。


Comparison operators

Comparison operators are used to judge magnitude or equality, and the result is always a Boolean.

== compares values (structural equality),=== compares references (whether it's the same object); the difference between the two is detailed in article 05, ""Kotlin Basic Data Types""

Example

fun main

(

)

{

    println

(

3

==

3

)

         

// true

    println

(

3

!=

4

)

         

// true

    println

(

3

<

4

)

// true

    println

(

3

4

)

           

// false

    println

(

3

<=

3

)

         

// true

    println

(

3

=

4

)

         

// false

   

// Strings are compared lexicographically

    println

(

"abc"

<

"abd"

)

// true

   

// Different types can be compared by magnitude, going through a compareTo overload

    println

(

3

<

3.5

)

// true

}



true

true

true

false

true

false

true

true

For a custom type to support comparison operators, it must implement the Comparable interface and override the compareTo method; this is covered in detail in the operator overloading article.


Logical operators

There are three logical operators:&&(AND),||(OR),!(NOT); operands must be Booleans.

&& and || They are all short-circuit operators: when the left side already determines the result, the right side is not evaluated.

Example

fun check

(

)

:

Boolean

{

    println

(

"check was called"

)

   

return

true

}

fun main

(

)

{

    val t

=

true

    val f

=

false

    println

(

t

&&

f

)

         

// false

    println

(

t

||

f

)

         

// true

    println

(

!

t

)

             

// false

   

// Short-circuit demo

    println

(

f

&&

check

(

)

)

   

// false; the left side is already false, so the right side is not evaluated

    println

(

t

||

check

(

)

)

   

// true; the left side is already true, so the right side is not evaluated

    println

(

t

&&

check

(

)

)

   

// true; the right side must be evaluated

}



false

true

false

false

true

check 被调用

true

Short-circuiting is often used to avoid null pointers: first check the object is not null, then access its members.

Example

fun main

(

)

{

    val name

:

String

?

=

null

   

// When the left side is false, the right side's name.length is not executed

   

if

(

name

!=

null

&&

name.

length

0

)

{

        println

(

"Name length: ${name.length}"

)

   

}

else

{

        println

(

"Name is empty"

)

 

// Name is empty

   

}

}



名字为空


Bitwise operations

Kotlin has no <<、>>、&、| such bitwise operators; instead it provides a set of named functions.

These functions are called in infix form for better readability, for example a shl 2 means shift left by two bits.

function Meaning Corresponding Java syntax
shl Shift left, fill low bits with 0 <<
shr Signed shift right, fill high bits with the sign bit >>
ushr Unsigned shift right, fill high bits with 0 >>>
and Bitwise AND &
or Bitwise OR |
xor Bitwise XOR ^
inv Bitwise invert; it's a normal function so parentheses are required ~

Example

fun main

(

)

{

    val a

=

0b1100    

// Decimal 12

    val b

=

0b1010    

// Decimal 10

    println

(

a and b

)

   

// 8,0b1000

    println

(

a or b

)

     

// 14,0b1110

    println

(

a xor b

)

   

// 6,0b0110

    println

(

a.

inv

(

)

)

   

// -13, bitwise inversion

    println

(

a shl

1

)

   

// 24, shifting left one bit equals multiplying by 2

    println

(

a shr

1

)

   

// 6, shifting right one bit equals dividing by 2

    println

(

8

shr

1

)

   

// -4, signed shift right preserves the sign bit

    println

(

8

ushr

1

)

 

// 2147483644, unsigned shift right fills high bits with 0

   

// Infix functions have lower precedence than arithmetic operators

    println

(

1

2

shl

3

)

// 24, compute 1 + 2 first then shift left 3 bits

}



8

14

6

-13

24

6

-4

2147483644

24

Note:Bitwise functions are defined only on Int and Long (as well as UInt and ULong); Byte and Short need to call toInt() to convert first, otherwise compilation fails.

The following example demonstrates two common uses of bitwise operations: extracting certain bits, and using bitmasks to represent multiple switches.

Example

fun main

(

)

{

    val color

=

0xFFCC00  

// A 24-bit RGB color

   

// Shift right 16 bits then take the low 8 bits to get the red component

    val red

=

(

color shr

16

)

and 0xFF

    val green

=

(

color shr

8

)

and 0xFF

    val blue

=

color and 0xFF

    println

(

"R=$red G=$green B=$blue"

)

 

// R=255 G=204 B=0

   

// Use bitmasks to represent multiple switches

    val READ

=

0b001

    val WRITE

=

0b010

    val EXEC

=

0b100

    var permission

=

READ or WRITE        

// Has read and write permissions

    println

(

permission

)

                 

// 3

    println

(

(

permission and READ

)

!=

0

)

 

// true, has read permission

    println

(

(

permission and EXEC

)

!=

0

)

 

// false, no execute permission

}



R=255 G=204 B=0

3

true

false


Range operators

A range represents a continuous sequence of values; Kotlin provides the closed range .. and the open range ..< in two forms.

1..5 contains all five numbers from 1 to 5,1..<5 contains 1 to 4, not 5.

..< introduced as an experimental feature in Kotlin 1.7.20, stable since Kotlin 1.9.

Syntax Meaning Example result
1..5 Closed range, includes the right endpoint [1, 2, 3, 4, 5]
1..<5 Open range, excludes the right endpoint, stable since Kotlin 1.9 [1, 2, 3, 4]
1 until 5 Equivalent to 1..<5 [1, 2, 3, 4]
5 downTo 1 Descending range [5, 4, 3, 2, 1]
1..10 step 3 Specify step [1, 4, 7, 10]

Example

fun main

(

)

{

    val closed

=

1

..

5

    println

(

closed

)

                   

// 1..5

    println

(

5

in closed

)

             

// true

    println

(

closed.

toList

(

)

)

         

// [1, 2, 3, 4, 5]

    val open

=

1

..

<

5

println

(

open

)

// 1..4

    println

(

5

in open

)

               

// false

    println

(

open.

toList

(

)

)

           

// [1, 2, 3, 4]

    println

(

(

1

until

5

)

.

toList

(

)

)

     

// [1, 2, 3, 4]

    println

(

(

5

downTo

1

)

.

toList

(

)

)

   

// [5, 4, 3, 2, 1]

    println

(

(

1

..

10

step

3

)

.

toList

(

)

)

 

// [1, 4, 7, 10]

    println

(

(

10

downTo

1

step

3

)

.

toList

(

)

)

 

// [10, 7, 4, 1]

   

// Characters can also form ranges

    println

(

(

'a'

..

'e'

)

.

toList

(

)

)

     

// [a, b, c, d, e]

}



1..5

true

[1, 2, 3, 4, 5]

1..4

false

[1, 2, 3, 4]

[1, 2, 3, 4]

[5, 4, 3, 2, 1]

[1, 4, 7, 10]

[10, 7, 4, 1]

[a, b, c, d, e]

downTo's step must be positive, and the value of step must also be greater than 0, otherwise an exception is thrown.

Common misuse:5..1 is an empty range and won't decrement automatically. To go from 5 down to 1 you must write 5 downTo 1。


in and !in

in used to determine whether a value belongs to a range, collection, or string,!in is its negation.

It essentially calls the object's contains function, so any type implementing contains can use it.

Example

fun main

(

)

{

   

// Check whether a number is within a range

    println

(

3

in

1

..

5

)

                 

// true

    println

(

9

!

in

1

..

5

)

               

// true

   

// Check whether a character is within a character range

    println

(

'c'

in

'a'

..

'z'

)

           

// true

    println

(

'C'

in

'a'

..

'z'

)

           

// false

   

// Check whether a substring appears in a string

    val site

=

"www.runoob.com"

    println

(

"runoob"

in site

)

         

// true

    println

(

"RUNOOB"

in site

)

         

// false, case-sensitive

    println

(

'r'

in site

)

               

// true

   

// Check whether an element is in a collection

    val names

=

listOf

(

"Runoob"

,

"Kotlin"

)

    println

(

"Runoob"

in names

)

         

// true

    println

(

"Java"

!

in names

)

         

// true

}



true

true

true

false

true

false

true

true

true

In a for loop,in means "iterate"; this is covered in the loop control article.


Operator Precedence

When multiple operators appear in one expression, those with higher precedence are evaluated first.

The table below is arranged from highest to lowest precedence; within the same row, operators associate from left to right.

Precedence operator Description
1 . ?. ++ -- Postfix, member access
2 - + ++ -- ! Prefix
3 * / % Multiplication, division, remainder
4 + - Additive
5 .. ..< Range
6 shl shr ushr and or xor until downTo step to Named infix functions
7 ?: Elvis operator
8 in !in is !is Containment and type checks
9 < > <= >= Magnitude comparison
10 == != === !== Equality
11 && Logical AND
12 || Logical OR
13 = += -= *= /= %= Assignment

If you can't remember precedence, adding parentheses is the safest approach and also makes code more readable.

Example

fun main

(

)

{

   

// && has higher precedence than ||

    println

(

true

||

false

&&

false

)

   

// true, equivalent to true || (false && false)

   

// Range operators have higher precedence than infix functions

    println

(

1

..

5

step

2

)

               

// 1..5 step 2

   

// Infix functions have lower precedence than arithmetic operators

    println

(

1

2

shl

3

)

               

// 24, equivalent to (1 + 2) shl 3

   

// Adding parentheses makes the intent clearer

    println

(

(

true

||

false

)

&&

false

)

 

// false

}



true

1..5 step 2

24

false

1..5 step 2 results in an IntProgression, which prints as 1..5 step 2 and converts to the list [1, 3, 5].


Common questions

Below are some of the most error-prone issues when using operators.

Why is the result of 5 / 2 equal to 2 instead of 2.5

Because both operands are Ints, Kotlin performs integer division and the fractional part is truncated.

To get a fractional result, just convert one operand with toDouble().

Does Kotlin have a ternary operator

No. Kotlin uses an if expression instead, for example val max = if (a > b) a else b, which is more readable.

Why aren't && and || always both evaluated

Because they use short-circuit evaluation: when the left side determines the result, the right side is not evaluated.

This feature both improves performance and is often used to avoid null pointers, but note that side effects on the right side may not execute.

The relationship between bit shifting and multiplication/division

Shifting left one bit is equivalent to multiplying by 2, and shifting right one bit to integer-dividing by 2; this holds only when there is no overflow.

Signed shift right shr preserves the sign bit, while unsigned shift right ushr fills high bits with 0; the results are completely different for negative numbers.

Why can't a = b be written in a condition

Because Kotlin's assignment is not an expression and has no return value, so it can't participate in a condition.

Splitting reading and checking into two steps actually makes the code clearer.