Kotlin Operators and Expressions
Previous | Table of Contents | Next |
Kotlin Data Types, Variables and Nullability | Kotlin Flow Control |
You are reading a sample chapter from the Android Studio 3.0 / Android 8 Edition book. Purchase the fully updated Android Studio 3.2 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format Android Studio 3.2 Development Essentials - Kotlin Edition Print and eBook (ePub/PDF/Kindle) editions contain 96 chapters and over 800 pages |
So far we have looked at using variables and constants in Kotlin and also described the different data types. Being able to create variables is only part of the story however. The next step is to learn how to use these variables in Kotlin code. The primary method for working with data is in the form of expressions.
Expression Syntax in Kotlin
The most basic expression consists of an operator, two operands and an assignment. The following is an example of an expression:
val myresult = 1 + 2
In the above example, the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to a variable named myresult. The operands could just have easily been variables (or a mixture of values and variables) instead of the actual numerical values used in the example.
In the remainder of this chapter we will look at the basic types of operators available in Kotlin.
The Basic Assignment Operator
We have already looked at the most basic of assignment operators, the = operator. This assignment operator simply assigns the result of an expression to a variable. In essence, the = assignment operator takes two operands. The left-hand operand is the variable to which a value is to be assigned and the right-hand operand is the value to be assigned. The right-hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation or a call to a function, the result of which will be assigned to the variable. The following examples are all valid uses of the assignment operator:
var x: Int // Declare a mutable Int variable val y = 10 // Declare and initialize an immutable Int variable x = 10 // Assign a value to x x = x + y // Assign the result of x + y to x x = y // Assign the value of y to x
You are reading a sample chapter from the Android Studio 3.0 / Android 8 Edition book. Purchase the fully updated Android Studio 3.2 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format Android Studio 3.2 Development Essentials - Kotlin Edition Print and eBook (ePub/PDF/Kindle) editions contain 96 chapters and over 800 pages |
Kotlin Arithmetic Operators
Kotlin provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-) which takes two operands (i.e. one value to be subtracted from another). For example:
var x = -10 // Unary - operator used to assign -10 to variable x x = x - 5 // Subtraction operator. Subtracts 5 from x
The following table lists the primary Kotlin arithmetic operators:
Operator | Description |
---|---|
-(unary) | Negates the value of a variable or expression |
* | Multiplication |
/ | Division |
+ | Addition |
- | Subtraction |
% | Remainder/Modulo |
Note that multiple operators may be used in a single expression.
For example:
x = y * 10 + z - 5 / 4
Augmented Assignment Operators
In an earlier section we looked at the basic assignment operator (=). Kotlin provides a number of operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows:
x = x + y
The above expression adds the value contained in variable x to the value contained in variable y and stores the result in variable x. This can be simplified using the addition compound assignment operator:
x += y
The above expression performs exactly the same task as x = x + y but saves the programmer some typing.
Numerous compound assignment operators are available in Kotlin. The most frequently used of which are outlined in the following table:
Operator | Description |
---|---|
x += y | Add x to y and place result in x |
x -= y | Subtract y from x and place result in x |
x *= y | Multiply x by y and place result in x |
x /= y | Divide x by y and place result in x |
x %= y | Perform Modulo on x and y and place result in x |
Increment and Decrement Operators
Another useful shortcut can be achieved using the Kotlin increment and decrement operators (also referred to as unary operators because they operate on a single operand). Consider the code fragment below:
x = x + 1 // Increase value of variable x by 1 x = x - 1 // Decrease value of variable x by 1
These expressions increment and decrement the value of x by 1. Instead of using this approach, however, it is quicker to use the ++ and -- operators. The following examples perform exactly the same tasks as the examples above:
x++ // Increment x by 1 x-- // Decrement x by 1
These operators can be placed either before or after the variable name. If the operator is placed before the variable name, the increment or decrement operation is performed before any other operations are performed on the variable. For example, in the following code, x is incremented before it is assigned to y, leaving y with a value of 10:
var x = 9 val y = ++x
In the next example, however, the value of x (9) is assigned to variable y before the decrement is performed. After the expression is evaluated the value of y will be 9 and the value of x will be 8.
var x = 9 val y = x--
Equality Operators
Kotlin also includes a set of logical operators useful for performing comparisons. These operators all return a Boolean result depending on the result of the comparison. These operators are binary operators in that they work with two operands. Equality operators are most frequently used in constructing program flow control logic. For example an if statement may be constructed based on whether one value matches another:
if x == y { // Perform task }
The result of a comparison may also be stored in a Boolean variable. For example, the following code will result in a true value being stored in the variable result: var result: Bool
val x = 10 val y = 20 result = x < y
Clearly 10 is less than 20, resulting in a true evaluation of the x < y expression. The following table lists the full set of Kotlin comparison operators:
Operator | Description |
---|---|
x == y | Returns true if x is equal to y |
x > y | Returns true if x is greater than y |
x >= y | Returns true if x is greater than or equal to y |
x < y | Returns true if x is less than y |
x <= y | Returns true if x is less than or equal to y |
x != y | Returns true if x is not equal to y |
You are reading a sample chapter from the Android Studio 3.0 / Android 8 Edition book. Purchase the fully updated Android Studio 3.2 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format Android Studio 3.2 Development Essentials - Kotlin Edition Print and eBook (ePub/PDF/Kindle) editions contain 96 chapters and over 800 pages |
Boolean Logical Operators
Kotlin also provides a set of so called logical operators designed to return Boolean true or false values. These operators both return Boolean results and take Boolean values as operands. The key operators are NOT (!), AND (&&) and OR (||).
The NOT (!) operator simply inverts the current value of a Boolean variable, or the result of an expression. For example, if a variable named flag is currently true, prefixing the variable with a ‘!’ character will invert the value to false:
val flag = true // variable is true val secondFlag = !flag // secondFlag set to false
The OR (||) operator returns true if one of its two operands evaluates to true, otherwise it returns false. For example, the following code evaluates to true because at least one of the expressions either side of the OR operator is true:
if ((10 < 20) || (20 < 10)) { print("Expression is true") } <pre> The AND (&&) operator returns true only if both operands evaluate to be true. The following example will return false because only one of the two operand expressions evaluates to true: <pre> if ((10 < 20) && (20 < 10)) { print("Expression is true") }
Range Operator
Kotlin includes a useful operator that allows a range of values to be declared. As will be seen in later chapters, this operator is invaluable when working with looping in program logic. The syntax for the range operator is as follows:
x..y
This operator represents the range of numbers starting at x and ending at y where both x and y are included within the range (referred to as a closed range). The range operator 5..8, for example, specifies the numbers 5, 6, 7 and 8.
Bitwise Operators
As previously discussed, computer processors work in binary. These are essentially streams of ones and zeros, each one referred to as a bit. Bits are formed into groups of 8 to form bytes. As such, it is not surprising that we, as programmers, will occasionally end up working at this level in our code. To facilitate this requirement, Kotlin provides a range of bit operators.
Those familiar with bitwise operators in other languages such as C, C++, C#, Objective-C and Java will find nothing new in this area of the Kotlin language syntax. For those unfamiliar with binary numbers, now may be a good time to seek out reference materials on the subject in order to understand how ones and zeros are formed into bytes to form numbers. Other authors have done a much better job of describing the subject than we can do within the scope of this book.
For the purposes of this exercise we will be working with the binary representation of two numbers. First, the decimal number 171 is represented in binary as:
10101011
Second, the number 3 is represented by the following binary sequence:
00000011
Now that we have two binary numbers with which to work, we can begin to look at the Kotlin bitwise operators:
Bitwise Inversion
The Bitwise inversion (also referred to as NOT) is performed using the inv() operation and has the effect of inverting all of the bits in a number. In other words, all the zeros become ones and all the ones become zeros. Taking our example 3 number, a Bitwise NOT operation has the following result:
00000011 NOT ======== 11111100
The following Kotlin code, therefore, results in a value of -4:
val y = 3 val z = y.inv() print("Result is $z")
Bitwise AND
The Bitwise AND is performed using the and() operation. It makes a bit by bit comparison of two numbers. Any corresponding position in the binary sequence of each number where both bits are 1 results in a 1 appearing in the same position of the resulting number. If either bit position contains a 0 then a zero appears in the result. Taking our two example numbers, this would appear as follows:
10101011 AND 00000011 ======== 00000011
As we can see, the only locations where both numbers have 1s are the last two positions. If we perform this in Kotlin code, therefore, we should find that the result is 3 (00000011):
val x = 171 val y = 3 val z = x.and(y) print("Result is $z")
Bitwise OR
The bitwise OR also performs a bit by bit comparison of two binary sequences. Unlike the AND operation, the OR places a 1 in the result if there is a 1 in the first or second operand. Using our example numbers, the result will be as follows:
10101011 OR 00000011 ======== 10101011
If we perform this operation in Kotlin using the or() operation the result will be 171:
val x = 171 val y = 3 val z = x.or(y) print("Result is $z")
Bitwise XOR
The bitwise XOR (commonly referred to as exclusive OR and performed using the xor() operation) performs a similar task to the OR operation except that a 1 is placed in the result if one or other corresponding bit positions in the two numbers is 1. If both positions are a 1 or a 0 then the corresponding bit in the result is set to a 0. For example:
10101011 XOR 00000011 ======== 10101000
The result in this case is 10101000 which converts to 168 in decimal. To verify this we can, once again, try some Kotlin code:
val x = 171 val y = 3 val z = x.xor(y) print("Result is $z")
When executed, we get the following output from print:
Result is 168
You are reading a sample chapter from the Android Studio 3.0 / Android 8 Edition book. Purchase the fully updated Android Studio 3.2 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format Android Studio 3.2 Development Essentials - Kotlin Edition Print and eBook (ePub/PDF/Kindle) editions contain 96 chapters and over 800 pages |
Bitwise Left Shift
The bitwise left shift moves each bit in a binary number a specified number of positions to the left. Shifting an integer one position to the left has the effect of doubling the value.
As the bits are shifted to the left, zeros are placed in the vacated right most (low order) positions. Note also that once the left most (high order) bits are shifted beyond the size of the variable containing the value, those high order bits are discarded:
10101011 Left Shift one bit ======== 101010110
In Kotlin the bitwise left shift operator is performed using the shl() operation, passing through the number of bit positions to be shifted. For example, to shift left by 1 bit:
val x = 171 val z = x.shl(1) print("Result is $z")
When compiled and executed, the above code will display a message stating that the result is 342 which, when converted to binary, equates to 101010110.
Bitwise Right Shift
A bitwise right shift is, as you might expect, the same as a left except that the shift takes place in the opposite direction. Shifting an integer one position to the right has the effect of halving the value.
Note that since we are shifting to the right there is no opportunity to retain the lower most bits regardless of the data type used to contain the result. As a result the low order bits are discarded. Whether or not the vacated high order bit positions are replaced with zeros or ones depends on whether the sign bit used to indicate positive and negative numbers is set or not.
10101011 Right Shift one bit ======== 01010101
The bitwise right shift is performed using the shr() operation passing through the shift count:
val x = 171 val z = x.shr(1) print("Result is $z")
When executed, the above code will report the result of the shift as being 85, which equates to binary 01010101.
Summary
Operators and expressions provide the underlying mechanism by which variables and constants are manipulated and evaluated within Kotlin code. This can take the simplest of forms whereby two numbers are added using the addition operator in an expression and the result stored in a variable using the assignment operator. Operators fall into a range of categories, details of which have been covered in this chapter.
You are reading a sample chapter from the Android Studio 3.0 / Android 8 Edition book. Purchase the fully updated Android Studio 3.2 / Android 9 / Jetpack Edition of this publication in eBook ($29.99) or Print ($45.99) format Android Studio 3.2 Development Essentials - Kotlin Edition Print and eBook (ePub/PDF/Kindle) editions contain 96 chapters and over 800 pages |
Previous | Table of Contents | Next |
Kotlin Data Types, Variables and Nullability | Kotlin Flow Control |