Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.1 Development Essentials – Kotlin Edition

You're reading from  Android Studio 4.1 Development Essentials – Kotlin Edition

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801815987
Pages 822 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (95) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Introduction to Kotlin 12. Kotlin Data Types,Variables and Nullability 13. Kotlin Operators and Expressions 14. Kotlin Flow Control 15. An Overview of Kotlin Functions and Lambdas 16. The Basics of Object Oriented Programming in Kotlin 17. An Introduction to Kotlin Inheritance and Subclassing 18. An Overview of Android View Binding 19. Understanding Android Application and Activity Lifecycles 20. Handling Android Activity State Changes 21. Android Activity State Changes by Example 22. Saving and Restoring the State of an Android Activity 23. Understanding Android Views, View Groups and Layouts 24. A Guide to the Android Studio Layout Editor Tool 25. A Guide to the Android ConstraintLayout 26. A Guide to using ConstraintLayout in Android Studio 27. Working with ConstraintLayout Chains and Ratios in Android Studio 28. An Android Studio Layout Editor ConstraintLayout Tutorial 29. Manual XML Layout Design in Android Studio 30. Managing Constraints using Constraint Sets 31. An Android ConstraintSet Tutorial 32. A Guide to using Apply Changes in Android Studio 33. An Overview and Example of Android Event Handling 34. Android Touch and Multi-touch Event Handling 35. Detecting Common Gestures using the Android Gesture Detector Class 36. Implementing Custom Gesture and Pinch Recognition on Android 37. An Introduction to Android Fragments 38. Using Fragments in Android Studio - An Example 39. Modern Android App Architecture with Jetpack 40. An Android Jetpack ViewModel Tutorial 41. An Android Jetpack LiveData Tutorial 42. An Overview of Android Jetpack Data Binding 43. An Android Jetpack Data Binding Tutorial 44. An Android ViewModel Saved State Tutorial 45. Working with Android Lifecycle-Aware Components 46. An Android Jetpack Lifecycle Awareness Tutorial 47. An Overview of the Navigation Architecture Component 48. An Android Jetpack Navigation Component Tutorial 49. An Introduction to MotionLayout 50. An Android MotionLayout Editor Tutorial 51. A MotionLayout KeyCycle Tutorial 52. Working with the Floating Action Button and Snackbar 53. Creating a Tabbed Interface using the TabLayout Component 54. Working with the RecyclerView and CardView Widgets 55. An Android RecyclerView and CardView Tutorial 56. A Layout Editor Sample Data Tutorial 57. Working with the AppBar and Collapsing Toolbar Layouts 58. An Android Studio Master/Detail Flow Tutorial 59. An Overview of Android Intents 60. Android Explicit Intents – A Worked Example 61. Android Implicit Intents – A Worked Example 62. Android Broadcast Intents and Broadcast Receivers 63. A Basic Overview of Threads and AsyncTasks 64. An Introduction to Kotlin Coroutines 65. An Android Kotlin Coroutines Tutorial 66. An Overview of Android Started and Bound Services 67. Implementing an Android Started Service – A Worked Example 68. Android Local Bound Services – A Worked Example 69. Android Remote Bound Services – A Worked Example 70. An Android Notifications Tutorial 71. An Android Direct Reply Notification Tutorial 72. Foldable Devices and Multi-Window Support 73. An Overview of Android SQLite Databases 74. The Android Room Persistence Library 75. An Android TableLayout and TableRow Tutorial 76. An Android Room Database and Repository Tutorial 77. Accessing Cloud Storage using the Android Storage Access Framework 78. An Android Storage Access Framework Example 79. Video Playback on Android using the VideoView and MediaController Classes 80. Android Picture-in-Picture Mode 81. An Android Picture-in-Picture Tutorial 82. Making Runtime Permission Requests in Android 83. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 84. Printing with the Android Printing Framework 85. An Android HTML and Web Content Printing Example 86. A Guide to Android Custom Document Printing 87. An Introduction to Android App Links 88. An Android Studio App Links Tutorial 89. A Guide to the Android Studio Profiler 90. An Android Biometric Authentication Tutorial 91. Creating, Testing and Uploading an Android App Bundle 92. An Overview of Android Dynamic Feature Modules 93. An Android Studio Dynamic Feature Tutorial 94. An Overview of Gradle in Android Studio Index

13. Kotlin Operators and Expressions

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.

13.1 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.

13.2 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

13.3 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:

...

13.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 augmented assignment operator:

x += y

The above expression performs exactly the same task as x = x + y but saves the programmer some typing.

Numerous augmented assignment operators are available in Kotlin. The most frequently used of which are outlined in the following table:

Operator

Description

-(unary)

Negates the value of a variable or expression

*

Multiplication

13.5 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...

13.6 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

...
...

13.7 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...

13.8 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.

13.9 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...

13.10 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.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Kotlin Edition
Published in: May 2021 Publisher: Packt ISBN-13: 9781801815987
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}