Kotlin

Kotlin for Beginners – Part 2: Flow of Control, Functions, and Arrays

Alright, lets now look at some more topics related to Kotlin programming, namely Flow of Control, Functions, Arrays

Kotlin – if expression

Conditional statements or if-else statement is written in Kotlin in a different manner.

There are mainly 3 ways of writing if – else expression:

• if – else
• if – else if – else ladder
• nested if

Kotlin if-else expression

```fun main(args: Array <String>) {
val number1 = 4
val number2 = 2
val finalResult = if (number1 > number2) {
"\$number1 is greater than \$number2"
} else {
"\$number1 is smaller than \$number2"
}
println(finalResult)
}
//Output
4 is greater than 2```

```fun main(args:  Array <String>){
val num = 2
val result = if(num>0) {
"\$num is positive number"
} else if(num<0){
"\$num is negative number"
} else {
"\$num is zero"
}
println(result)
}```

Kotlin nested if expression

```fun main(args: Array<String>) {
val number1 = 5
val number2 = 10
val number3 = 15
val finalresult = if (number1 > number2){
val maxnumber = if(number1 > number3){
number1
}else{
number3
}
"if "+maxnumber
}else if(number2 > number3){
"else if"+number2
}else{
"else "+number3
}
println("\$finalresult")
}```

Kotlin – when expression

In this language, ‘when’ is used in place of ‘switch’ serving same purpose.

Simple example:

```fun main(args: Array<String>){
var days = 7
var day = when(days) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day name"
}
println("You entered \$day")
}

//Output:
You entered Sunday```

when without expression

```fun main(args: Array<String>){
var days = 7
when(days) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
else -> println("Invalid day")
}
}```

when in multiple statements

```fun main(args: Array<String>){
var day = 1
when(day) {
1 -> {
println("Monday")
println("First day of the week")
}
2 -> println("Tuesday")
else -> println("Other days")
}
}

//Output:
First day of the week```

when and multiple branches

```fun main(args: Array<String>){
var number = 10
when(number) {
2, 4, 6, 8, 10 ->
println("Even number")
1, 3, 9, 11 ->
println("Odd number")
0 ->
println("whole number")
else -> println("invalid input")
}
}

//Output:
Even number```

when in range

Range is created using ..(double dot) operator and ‘in’ operator is used to check whether the value belongs to a range.

```fun main(args: Array<String>){
var num = 2
when(num) {
in 1..5 -> println("Number is in the range 1 to 5")
in 6..10 -> println("Number is in the range 6 to 10")
}
}

//Output:
Number is in the range 1 to 5```

Kotlin – loops

for loop

In Kotlin,  for loop is just like a foreach loop in Java/C#  and it is used to iterate a part of program several times. It iterates through arrays, ranges, collections and other things where iterations are there.

Simple example of iterating in an array:

```fun main(args : Array<String>) {
val employeeid = arrayOf(101,102,103,104,105)
for(id in employeeid){
println(id)
}
}

//Output:
101
102
103
104
105```

Just like normal for loop in other languages. It is not required to enclose within curly braces { }, if body of for – loop has only one single line of statement.

We can also iterate elements on the basis of index in array.

Simple example:

```fun main(args : Array<String>) {
val empid = arrayOf(101,102,103,104,105)
for(e in empid.indices)
println("empid[\$e]: "+ empid[e])
}

//Output:
empid[0]: 101
empid[1]: 102
empid[2]: 103
empid[3]: 104
empid[4]: 105```

while loop

When we need to iterate a part of a program several times till a particular condition is true, we use while loop.

Simple example:

```fun main(args: Array<String>){
var i = 0
while (i<6){
println(i)
i++
}
}

//Output:
0
1
3
4
5```

do-while loop

In Kotlin, do-while is written similar to normal do-while loop but includes “;”.

Simple example:

```fun main(args: Array<String>){
var i = 0
do {
println(i)
i++
}
while (i<6);
}
//Output:
0
1
2
3
4
5
```

Jump statements in Kotlin

There are 3 kinds of Jump statements in Kotlin:

• break
• continue
• return

First, lets look at break statement:

```fun main(args: Array<String>) {
for (i in 1..5) {
if (i == 4) {
break
}
println(i)
}
}

//Output:
1
2
3```

In above example, when value of i became equal to 4 and satisfy the if  ( i == 4 ) than the break expression execute and termination  of for loop takes place.

Another kind of break expression is Kotlin labeled break expression. Example given below:

```fun main(args: Array<String>) {
loop@ for (i in 1..5) {
for (j in 1..5) {
println("i = \$i and j = \$j")
if (i == 3)
break@loop
}
}
}

//Output:
i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 1 and j = 4
i = 1 and j = 5
i = 2 and j = 1
i = 2 and j = 2
i = 2 and j = 3
i = 2 and j = 4
i = 2 and j = 5
```

In Kotlin, continue statement is used to continue the current flow of the program and skips remaining code at a specified condition. It affects the inner loop only, if present within a nested loop.

```fun main(args: Array<String>) {
for (i in 1..3) {
println("i = \$i")
if (j == 2) {
continue
}
println("its below if")
}
}

//Output:
i = 1
its below if
i = 2
i = 3
its below if```

We also have labeled continue statement. See the example:

```fun main(args: Array<String>) {
labelname@ for (i in 1..3) {
for (j in 1..3) {
println("i = \$i and j = \$j")
if (i == 2) {
continue@labelname
}
println("its below if")
}
}
}

//Output:
i = 1 and j = 1
its below if
i = 1 and j = 2
its below if
i = 1 and j = 3
its below if
i = 2 and j = 1
i = 3 and j = 1
its below if
i = 3 and j = 2
its below if
i = 3 and j = 3
its below if```

Kotlin – functions

If you have reached to this point, it shows your committment towards learning Kotlin. Okay, let’s dive deep into Kotlin functions.

Functions in Kotlin are declared using fun keyword. The two kinds are defined here:

• Standard library function
• User defined function

Standard library function

Also, known as built-in library functions or pre-defined functions in general case.

Simple example:

```fun main(args: Array<String>) {
val base = 2
val exponent = 3
val result = Math.pow(base.toDouble(), exponent.toDouble())
}
//Output:

```

Here, pow() is a library function which returns result of a number till its power (Double value).

User defined function

Its just like any other function created by user. It takes an input, processes it and return its value.

Simple example:

```fun main(args: Array<String>){
sum()
}
fun sum(){
var num1 = 2
var num2 = 3
}

//Output:

Kotlin – parameterize function

Simple example:

```fun main(args: Array<String>){
val result = sum(2, 3)
print(result)
}
fun sum(number1: Int, number2:Int): Int{
}

//Output:
5```

Advance topics like Recursion function, default and named arguments, lambdas, high order functions and inline functions will be covered in next series: Kotlin for Intermediate level.

Kotlin – arrays

In Kotlin, Array is mutable in nature with fixed size meaning, we can perform both read and write operations on its elements.

Array constructor

We can declare array constructor with size and init function. The init function is used to return the elements of array along with their index.

`Array(size: Int, init: (Int) -> T)`

We can also declare array using arrayOf(), intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), byteArrayOf() functions.

For complete information on Arrays in Kotlin, please visit: Array – Kotlin Programming Language

Array declaration – using arrayOf() function

Simple example:

```var myArray1 = arrayOf(1,2,3,4,5)
var myArray2 = arrayOf<Int>(1,2,3,4,5)
val myArray3 = arrayOf<String>("John","Michael","Mandy","Raphael","Akoni")
var myArray4= arrayOf(1, "Amalo","Shanky")```

Array declaration – using intArrayOf() function

Simple example:

`var myArray5: IntArray = intArrayOf(1,2,3,4,5)`

We can also use set and get methods in Kotlin to modify or access particular elements of an array.

The set() function is used to set element at particular index location and get() function is used to get element from specified index.

Simple example:

set() function

```fun main(args: Array<String>) {
val array1 = arrayOf(1,2,3,4)
array1.set(0,5)
array1[2] = 6
for(element in array1){
println(element)
}
println()
}

//Output:
5
2
6
4```

get() function

```fun main(args: Array<String>) {
val array1 = arrayOf(1,2,3,4)
println(array1.get(0))
println(array1[2])
println()
}

//Output:
2
4```

Array: Simple example:

```fun main(args : Array<String>){
var array1 = arrayOf(1, 2, 3, 4, 5)
println("Size of array is: \${array.size}")
}

//Output:
Size of array is: 5```

String will be covered in Kotlin for Intermediate level

For further reading, please visit Kotlin for Beginners – Part 3: Exception Handling and Null Safety

Passionate about Mobile App Development. Trained in Java, Android, IOS Development, Databases, MEAN Stack and SAP. Strong communication, interpersonal, logical and team-building skills with proficiency in grasping new concepts quickly and utilizing the same in a productive manner. Apart from technical skills, Motivator, YouTuber, and Yogi.