Book Image

Hands-On Object-Oriented Programming with Kotlin

By : Abid Khan, Igor Kucherenko
Book Image

Hands-On Object-Oriented Programming with Kotlin

By: Abid Khan, Igor Kucherenko

Overview of this book

Kotlin is an object-oriented programming language. The book is based on the latest version of Kotlin. The book provides you with a thorough understanding of programming concepts, object-oriented programming techniques, and design patterns. It includes numerous examples, explanation of concepts and keynotes. Where possible, examples and programming exercises are included. The main purpose of the book is to provide a comprehensive coverage of Kotlin features such as classes, data classes, and inheritance. It also provides a good understanding of design pattern and how Kotlin syntax works with object-oriented techniques. You will also gain familiarity with syntax in this book by writing labeled for loop and when as an expression. An introduction to the advanced concepts such as sealed classes and package level functions and coroutines is provided and we will also learn how these concepts can make the software development easy. Supported libraries for serialization, regular expression and testing are also covered in this book. By the end of the book, you would have learnt building robust and maintainable software with object oriented design patterns in Kotlin.
Table of Contents (14 chapters)

Introduction to loops

A loop is a cyclic code, routine, or statement that is defined once but may run several times, and can perform a set of instructions indefinitely or repeatedly (once for each of a collection of items, or until a condition is met). If we were asked to print numbers from 1 to 3 on the screen, this could have been done easily by writing the code using the three println statements. If we were to print hundreds or thousands of numbers, for example, we would need a better solution for performing one task repeatedly for as long as required. Loops are a great solution for these situations, and they are dependent on three parts:

  • Start: Defining the beginning of the loop
  • Body: Defining the code block to execute it on each iteration
  • Controller: Defining when the loop should stop

In Kotlin there are two type of loops available:

  • Condition-controlled loop:
    • While loop
    • Do while loop
  • Count-controlled loop:
    • For loop

The while loop

A while loop is a statement or code that executes repeatedly based on a given condition. The while loop checks the condition before the block is executed. Similar to an if statement, the condition is assessed to see if the condition is true, and if so, the code within the block will execute, and the process will repeat until the condition becomes false. The while loop is useful when we want to perform one task as long as the condition remains true. Let's take a look at how to write a while loop in the following sections.

The while statement is followed by the condition defined within parentheses—( condition ).

Defining the while loop

The construct of while is similar to an if statement. Both of these work with conditions before executing the code block within. See the following example. Here, an if statement was written with a simple print line statement:

if(i <= 3) {
println("Print $i")
}

while(i <= 3) {
println("Print $i")
}

Once you have replaced the if with the while statement, the while loop is ready to use. However, do not forget to increment the value of i, otherwise the while loop will execute forever:

fun main(args: Array<String>) {
println("While loop")
var i = 1
while (i <= 3) {
println("While $i")
i++
}
}

This loop will execute three times and it will increment the value of i by one on each iteration. On the fourth iteration, the value of i will be 4 and the controlling statement will become false.

The do while loop

A do while loop executes a block of code at least once, and then repeatedly executes the block (or not) depending on a given condition at the end of the block. This is a minor variation of the while loop. In do while, the body executes before the condition is verified, therefore executing the code block at least once:

fun main(args: Array<String>) {
println("Do While loop")
var j = 1
do {
println(j)
j++
} while( j < 5 )
}

In this example, variable j is initialized with value 1, the do block prints the value of j and increments it, while block verifies the condition. The loop will continues until the value of j is less than 5.

The for loop

A for loop is used to specify an iteration that allows code to be executed repeatedly. This is a famous loop because of its flexibility and convenience. The for loop works with lists, arrays, collections, or ranges; it can be a range of integers or a collection of objects. The for loop also requires a control variable with start and end values, iterates on a given range, and exits the loop automatically. In a nutshell, it takes care of most things that other loops are not able to take care of.

Defining the for loop

The following points are necessary to create a for loop:

  • Declare a range with a start and end point. Ranges are defined with two dots, .., for example, var range = 1..3
  • With a for loop, create a variable and assign a range with in operator.
  • Define a code block that will execute a task:
fun main(args: Array<String>) {
var range = 1..3
for (i in range) {
println("value of $i")
}
}

On the first iteration, the for loop initializes the i variable with the first value of the range, and on each iteration the next value from the range will be assigned to i.

Any object that has an iterator function implemented can be used inside a for loop, for example, range, list, array, and so on.

With each iteration, the for loop assigns the next member from the range, which can be utilized as a normal member variable. In this example, each value from the range is printed on the screen:

fun main(args: Array<String>) {
val list = listOf(1,2,3,4)
for (l in list){
println("value of $l")
}

val message = "kotlin is awesome"
for (m in message){
println(m)
}
}

The for loop with ranges and iterator will be discussed in Chapter 5, Data Collection, Iterators, and Filters.

The nested for loop

A for loop within a for loop is called a nested for loop. The outer for loop will assign a value from range to i, and the inner for loop will assign a value from range to j, and both values will be printed in the inner for loop:

for (i in 1..3) {
for (j in 1..3) {
println("$i , $j")
}
}

Notice that on each iteration of the outer for loop, the inner for loop will be executed three times.

Break statements

Kotlin provides break statements, which are used to break the continuation of a loop. Break statements immediately terminate the iteration of a loop when the test condition is met. This is often used in while, do while, and for loops in order to end the current loop and exit where conditions may need to be defined inside the loop for specific reasons:

fun main(args: Array<String>) {
for (i in 1..10) {
println("For $i")
if(i >= 5) {
break;
}
}
}

Notice that the break statement terminates the program execution where it is placed. If the break statement is in an inner loop, the outer loop will perform its task normally. This is because only the inner loop will end and the outer loop will continue its iterations as defined until it fulfills its condition. Take an example of a nested loop and print the value of i and j but break the inner loop when both values are same:

for (i in 1..3) {
for (j in 1..3) {
println("$i , $j")
if(i==j) {
break;
}
}
}

The break statement with labeled for loop

Break statements always break the nearest or parent loop where the break is placed, as we saw in previous example. But what if we want to stop the loop iterations altogether whenever a certain condition is met in a nested inner loop? To address such conditions, Kotlin provides a concept called a labeled for loop. This means that an alias name is assigned to a for loop to break it by using the break@nameOfTheLoop statement. Assign a name to the for loop, as described here, and call the loop by using the break statement. When the variables i and j are equal to 2, by using break@outLoop, the break statement would know which for loop to terminate:

fun main(args: Array<String>) {

println("Labled For Loop")
outLoop@ for (i in 1..3) {
for (j in 1..3) {
if(i==2 && j==2) {
break@outLoop
}
println("$i , $j")
}
}
}

So, the outer for loop would run once and the inner for loop would execute its body three times. On the second iteration of the outer loop, when both i and j would equal 2, the break statement would call the outer loop to terminate. So, if the outer loop terminates, this means that the inner loop terminates automatically.