Kotlin Getters and Setters

In this article, you will learn to use getters and setters in Kotlin with the help of an example.

Before you learn about getters and setter, be sure to check Kotlin class and objects.

In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property.

In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.


How getters and setters work?

The following code in Kotlin

class Person {
    var name: String = "defaultValue"
}

is equivalent to

class Person {
    var name: String = "defaultValue"

    // getter
    get() = field

    // setter
    set(value) {
        field = value
    }
}

When you instantiate object of the Person class and initialize the name property, it is passed to the setters parameter value and sets field to value.

val p = Person()
p.name = "jack"

Now, when you access name property of the object, you will get field because of the code get() = field.

println("${p.name}")

Here’s an working example:

fun main(args: Array<String>) {

    val p = Person()
    p.name = "jack"
    println("${p.name}")
}

class Person {
    var name: String = "defaultValue"

    get() = field

    set(value) {
        field = value
    }
}

When you run the program, the output will be:

jack

This is how getters and setters work by default. However, you can change value of the property (modify value) using getters and setters.


Example: Changing value of the property

fun main(args: Array<String>) {

    val maria = Girl()
    maria.actualAge = 15
    maria.age = 15
    println("Maria: actual age = ${maria.actualAge}")
    println("Maria: pretended age = ${maria.age}")

    val angela = Girl()
    angela.actualAge = 35
    angela.age = 35
    println("Angela: actual age = ${angela.actualAge}")
    println("Angela: pretended age = ${angela.age}")
}

class Girl {
    var age: Int = 0
    get() = field
    set(value) {
        field = if (value < 18)
            18
        else if (value >= 18 && value <= 30)
            value
        else
            value-3
    }

    var actualAge: Int = 0
}

When you run the program, the output will be:

Maria: actual age = 15
Maria: pretended age = 18
Angela: actual age = 35
Angela: pretended age = 32

Here, the actualAge property works as expected.

However, there is additional logic is setters to modify value of the age property.

Kotlin Constructors

In this article, you will learn about constructors in Kotlin (both primary and secondary constructors) as well as initializer blocks with the help of examples.

A constructor is a concise way to initialize class properties.

It is a special member function that is called when an object is instantiated (created). However, how they work in Kotlin is slightly different.

In Kotlin, there are two constructors:

  • Primary constructor – concise way to initialize a class
  • Secondary constructor – allows you to put additional initialization logic

Primary Constructor

The primary constructor is part of the class header. Here’s an example:

class Person(val firstName: String, var age: Int) {
    // class body
}

The block of code surrounded by parentheses is the primary constructor: (val firstName: String, var age: Int).

The constructor declared two properties: firstName (read-only property as it’s declared using keyword val) and age (read-write property as it is declared with keyword var).


Example: Primary Constructor

fun main(args: Array<String>) {

    val person1 = Person("Joe", 25)

    println("First Name = ${person1.firstName}")
    println("Age = ${person1.age}")
}

class Person(val firstName: String, var age: Int) {

}

When you run the program, the output will be:

First Name = Joe
Age = 25

When the object of Person class is created, "Joe" and 25 values are passed as if Person is a function.

This initializes firstName and age properties of person1 object to "Joe" and 25 respectively.


There are other ways of using primary constructors.


Primary Constructor and Initializer Blocks

The primary constructor has a constrained syntax, and cannot contain any code.

To put the initilization code (not only code to initialize properties), initializer block is used. It is prefixed with init keyword. Let’s modify the above example with initializer block:

fun main(args: Array<String>) {
    val person1 = Person("joe", 25)
}

class Person(fName: String, personAge: Int) {
    val firstName: String
    var age: Int

    // initializer block
    init {
        firstName = fName.capitalize()
        age = personAge

        println("First Name = $firstName")
        println("Age = $age")
    }
}

When you run the program, the output will be:

First Name = Joe
Age = 25

Here, parameters fName and personAge inside the parenthesis accepts values "Joe" and 25 respectively when person1 object is created. However, fName and personAge are used without using var or val, and are not properties of the Person class.

The Person class has two properties firstName, and age are declared.

When person1 object is created, code inside initializer block is executed. The initializer block not only initializes its properties but also prints them.


Here is another way to perform the same task:

fun main(args: Array<String>) {
    val person1 = Person("joe", 25)
}

class Person(fName: String, personAge: Int) {
    val firstName = fName.capitalize()
    var age = personAge

    // initializer block
    init {
        println("First Name = $firstName")
        println("Age = $age")
    }
}

To distinguish the constructor parameter and property, different names are used (fName and firstName, and personAge and age). It’s more common to use _firstName and _age instead of completely different name for constructor parameters. For example:

class Person(_firstName: String, _age: Int) {
    val firstName = _firstName.capitalize()
    var age = _age

    // initializer block
    init {
        ... .. ...
    }
}

Default Value in Primary Constructor

You can provide default value to constructor parameters (similar to providing default arguments to functions). For example:

fun main(args: Array<String>) {

    println("person1 is instantiated")
    val person1 = Person("joe", 25)

    println("person2 is instantiated")
    val person2 = Person("Jack")

    println("person3 is instantiated")
    val person3 = Person()
}

class Person(_firstName: String = "UNKNOWN", _age: Int = 0) {
    val firstName = _firstName.capitalize()
    var age = _age

    // initializer block
    init {
        println("First Name = $firstName")
        println("Age = $age\n")
    }
}

When you run the program, the output will be:

First Name = Joe
Age = 25

person2 is instantiated
First Name = Jack
Age = 0

person3 is instantiated
First Name = UNKNOWN
Age = 0

Kotlin Secondary Constructor

In Kotlin, a class can also contain one or more secondary constructors. They are created using constructor keyword.

Secondary constructors are not that common in Kotlin. The most common use of secondary constructor comes up when you need to extend a class that provides multiple constructors that initialize the class in different ways. Be sure to check Kotlin Inheritance before you learn it.

Here’s how you can create a secondary constructor in Kotlin:

class Log {
    constructor(data: String) {
        // some code
    }
    constructor(data: String, numberOfData: Int) {
        // some code
    }
}

Here, the Log class has two secondary constructors, but no primary constructor.

You can extend the class as:

class Log {
    constructor(data: String) {
        // code
    }
    constructor(data: String, numberOfData: Int) {
        // code
    }
}

class AuthLog: Log {
    constructor(data: String): super(data) {
        // code
    }
    constructor(data: String, numberOfData: Int): super(data, numberOfData) {
        // code
    }
}

Here, constructors of the derived class AuthLog calls the corresponding constructor of the base class Log. For that, super() is used.

Calling constructor of base class from derived class.

In Kotlin, you can also call a constructor from another constructor of the same class (like in Java) using this().

class AuthLog: Log {
    constructor(data: String): this(data, 10) {
        // code
    }
    constructor(data: String, numberOfData: Int): super(data, numberOfData) {
        // code
    }
}
Calling constructor from the same class.

Example: Kotlin Secondary Constructor

fun main(args: Array<String>) {

    val p1 = AuthLog("Bad Password")
}

open class Log {
    var data: String = ""
    var numberOfData = 0
    constructor(_data: String) {

    }
    constructor(_data: String, _numberOfData: Int) {
        data = _data
        numberOfData = _numberOfData
        println("$data: $numberOfData times")
    }
}

class AuthLog: Log {
    constructor(_data: String): this("From AuthLog -> " + _data, 10) {
    }

    constructor(_data: String, _numberOfData: Int): super(_data, _numberOfData) {
    }
}

When you run the program, the output will be:

From AuthLog -> Bad Password: 10 times

Note: The secondary constructor must initialize the base class or delegate to another constructor (like in above example) if the class has no primary constructor.

Kotlin Recursion (Recursive Function) and Tail Recursion

In this article, you will learn to create recursive functions; a function that calls itself. Also, you will learn about tail recursive function.

A function that calls itself is known as recursive function. And, this technique is known as recursion.

A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.


How does recursion work in programming?

fun main(args: Array<String>) {
    ... .. ...
    recurse()
    ... .. ...
}

fun recurse() {
    ... .. ...
    recurse()
    ... .. ...
}

Here, the recurse() function is called from the body of recurse() function itself. Here’s how this program works:

Recursive function call in Kotlin

Here, the recursive call continues forever causing infinite recursion.

To avoid infinite recursion, if…else (or similar approach) can be used where one branch makes the recursive call and other doesn’t.


Example: Find factorial of a Number using Recursion

fun main(args: Array<String>) {
    val number = 4
    val result: Long

    result = factorial(number)
    println("Factorial of $number = $result")
}

fun factorial(n: Int): Long {
    return if (n == 1) n.toLong() else n*factorial(n-1)
}

When you run the program, the output will be:

Factorial of 4 = 24

How this program works?

The recursive call of the factorial() function can be explained in the following figure:

Here are the steps involved:

factorial(4)              // 1st function call. Argument: 4
4*factorial(3)            // 2nd function call. Argument: 3
4*(3*factorial(2))        // 3rd function call. Argument: 2
4*(3*(2*factorial(1)))    // 4th function call. Argument: 1 
4*(3*(2*1))                 
24

Kotlin Tail Recursion

Tail recursion is a generic concept rather than the feature of Kotlin language. Some programming languages including Kotlin use it to optimize recursive calls, whereas other languages (eg. Python) do not support them.


What is tail recursion?

In normal recursion, you perform all recursive calls first, and calculate the result from return values at last (as show in the above example). Hence, you don’t get result until all recursive calls are made.

In tail recursion, calculations are performed first, then recursive calls are executed (the recursive call passes the result of your current step to the next recursive call). This makes the recursive call equivalent to looping, and avoids the risk of stack overflow.


Condition for tail recursion

A recursive function is eligible for tail recursion if the function call to itself is the last operation it performs. For example,

Example 1: Not eligible for tail recursion because the function call to itself n*factorial(n-1) is not the last operation.

fun factorial(n: Int): Long {

    if (n == 1) {
        return n.toLong()
    } else {
        return n*factorial(n - 1)     
    }
}

Example 2: Eligible for tail recursion because function call to itself fibonacci(n-1, a+b, a) is the last operation.

fun fibonacci(n: Int, a: Long, b: Long): Long {
    return if (n == 0) b else fibonacci(n-1, a+b, a)
}

To tell compiler to perform tail recursion in Kotlin, you need to mark the function with tailrec modifier.


Example: Tail Recursion

import java.math.BigInteger

fun main(args: Array<String>) {
    val n = 100
    val first = BigInteger("0")
    val second = BigInteger("1")

    println(fibonacci(n, first, second))
}

tailrec fun fibonacci(n: Int, a: BigInteger, b: BigInteger): BigInteger {
    return if (n == 0) a else fibonacci(n-1, b, a+b)
}

When you run the program, the output will be:

354224848179261915075

This program computes the 100th term of the Fibonacci series. Since, the output can be a very large integer, we have imported BigInteger class from Java standard library.

Here, the function fibonacci() is marked with tailrec modifier and the function is eligible for tail recursive call. Hence, the compiler optimizes the recursion in this case.


If you try to find the 20000th term (or any other big integer) of the Fibonacci series without using tail recursion, the compiler will throw java.lang.StackOverflowError exception. However, our program above works just fine. It’s because we have used tail recursion which uses efficient loop based version instead of traditional recursion.


Example: Factorial Using Tail Recursion

The example to compute factorial of a number in the above example (first example) cannot be optimized for tail recursion. Here’s a different program to perform the same task.

fun main(args: Array<String>) {
    val number = 5
    println("Factorial of $number = ${factorial(number)}")
}

tailrec fun factorial(n: Int, run: Int = 1): Long {
    return if (n == 1) run.toLong() else factorial(n-1, run*n)
}

When you run the program, the output will be:

Factorial of 5 = 120

The compiler can optimize the recursion in this program as the recursive function is eligible for tail recursion, and we have used tailrec modifier that tells compiler to optimize the recursion.

Kotlin Default and Named Arguments

In this article, you will learn about default and named arguments with the help of examples.

Kotlin Default Argument

In Kotlin, you can provide default values to parameters in function definition.

If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default argument are used.


How default arguments works?

Case I: All arguments passed


Both arguments passed to the function

The function foo() takes two arguments. The arguments are provided with default values. However, foo() is called by passing both arguments in the above program. Hence, the default arguments are not used.

The value of letter and number will be 'x' and 2 respectively inside the foo() function.

Case II: All arguments are not passed


All arguments are not passed to the function

Here, only one (first) argument is passed to the foo() function. Hence, the first argument uses the value passed to the function. However, second argument number will take the default value since the second argument is not passed during function call.

The value of letter and number will be 'y' and 15 respectively inside the foo() function.

Case III: No argument is passed


No arguments passed to the function

Here, the foo() function is called without passing any argument. Hence, both arguments uses its default values.

The value of letter and number will be 'a' and 15 respectively inside the foo() function.


Example: Kotlin Default Argument

fun displayBorder(character: Char = '=', length: Int = 15) {
    for (i in 1..length) {
        print(character)
    }
}

fun main(args: Array<String>) {
    println("Output when no argument is passed:")
    displayBorder()

    println("\n\n'*' is used as a first argument.")
    println("Output when first argument is passed:")
    displayBorder('*')

    println("\n\n'*' is used as a first argument.")
    println("5 is used as a second argument.")
    println("Output when both arguments are passed:")
    displayBorder('*', 5)

}

When you run the program, the output will be:

Output when no argument is passed:
===============

'*' is used as a first argument.
Output when first argument is passed:
***************

'*' is used as a first argument.
5 is used as a second argument.
Output when both arguments are passed:
*****

Kotlin named argument

Before talking about named argument, let us consider a little modification of the above code:

fun displayBorder(character: Char = '=', length: Int = 15) {
    for (i in 1..length) {
        print(character)
    }
}

fun main(args: Array<String>) {
    displayBorder(5)
}

Here, we are trying to pass second argument to the displayBorder() function, and use default argument for first argument. However, this code will give use an error. It’s because the compiler thinks we are trying to provide 5 (Int value) to character (Char type).

To solve this situation, named arguments can be used. Here’ how:


Example: Kotlin named argument

fun displayBorder(character: Char = '=', length: Int = 15) {
    for (i in 1..length) {
        print(character)
    }
}

fun main(args: Array<String>) {
    displayBorder(length = 5)
}

When you run the program, the output will be:

=====

In the above program, we are using named argument (length = 5) specifying that the length parameter in the function definition should take this value (doesn’t matter the position of the argument).

Named Arguments in Kotlin

The first argument character uses the default value '=' in the program.

Kotlin Functions

In this article, you’ll learn about functions; what functions are, its syntax and how to create a user-function in Kotlin.

In programming, function is a group of related statements that perform a specific task.

Functions are used to break a large program into smaller and modular chunks. For example, you need to create and color a circle based on input from the user. You can create two functions to solve this problem:

  • createCircle() Function
  • colorCircle() Function

Dividing a complex program into smaller components makes our program more organized and manageable.

Furthermore, it avoids repetition and makes code reusable.


Types of Functions

Depending on whether a function is defined by the user, or available in standard library, there are two types of functions:

  • Kotlin Standard Library Function
  • User-defined functions

Kotlin Standard Library Function

The standard library functions are built-in functions in Kotlin that are readily available for use. For example,

  • print() is a library function that prints message to the standard output stream (monitor).
  • sqrt() returns square root of a number (Double value)
fun main(args: Array<String>) {

    var number = 5.5
    print("Result = ${Math.sqrt(number)}")
}

When you run the program, the output will be:

Result = 2.345207879911715

Here is a link to the Kotlin Standard Library for you to explore.


User-defined Functions

As mentioned, you can create functions yourself. Such functions are called user-defined functions.


How to create a user-defined function in Kotlin?

Before you can use (call) a function, you need to define it.

Here’s how you can define a function in Kotlin:

fun callMe() {
    // function body
}

To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe.

In the above program, the parenthesis ( ) is empty. It means, this function doesn’t accept any argument. You will learn about arguments later in this article.

The codes inside curly braces { } is the body of the function.


How to call a function?

You have to call the function to run codes inside the body of the function. Here’s how:

callme()

This statement calls the callMe() function declared earlier.

Function call in Koltin

Example: Simple Function Program

fun callMe() {
    println("Printing from callMe() function.")
    println("This is cool (still printing from inside).")
}

fun main(args: Array<String>) {
    callMe()
    println("Printing outside from callMe() function.")
}

When you run the program, the output will be:

Printing from callMe() function.
This is cool (still printing from inside).
Printing outside from callMe() function.

The callMe() function in the above code doesn’t accept any argument.

Also, the function doesn’t return any value (return type is Unit).

Let’s take another function example. This function will accept arguments and also returns a value.


Example: Add Two Numbers Using Function

fun addNumbers(n1: Double, n2: Double): Int {
    val sum = n1 + n2
    val sumInteger = sum.toInt()
    return sumInteger
}

fun main(args: Array<String>) {
    val number1 = 12.2
    val number2 = 3.4
    val result: Int

    result = addNumbers(number1, number2)
    println("result = $result")
}

When you run the program, the output will be:

result = 15

How functions with arguments and return value work?

Here, two arguments number1 and number2 of type Double are passed to the addNumbers() function during function call. These arguments are called actual arguments.

result = addNumbers(number1, number2)

The parameters n1 and n2 accepts the passed arguments (in the function definition). These arguments are called formal arguments (or parameters).

Passing arguments to a function in Kotlin

In Kotlin, arguments are separated using commas. Also, the type of the formal argument must be explicitly typed.

Note that, the data type of actual and formal arguments should match, i.e., the data type of first actual argument should match the type of first formal argument. Similarly, the type of second actual argument must match the type of second formal argument and so on.


Here,

return sumInteger

is the return statement. This code terminates the addNumbers() function, and control of the program jumps to the main() function.

In the program, sumInteger is returned from addNumbers() function. This value is assigned to the variable result.

Return value from a function in Kotlin

Notice,

  • both sumInteger and result are of type Int.
  • the return type of the function is specified in the function definition.// return type is Int fun addNumbers(n1: Double, n2: Double): Int { … .. … }

If the function doesn’t return any value, its return type is Unit. It is optional to specify the return type in the function definition if the return type is Unit.


Example: Display Name by Using Function

fun main(args: Array<String>) {
    println(getName("John", "Doe"))
}

fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

When you run the program, the output will be:

John Doe

Here, the getName() function takes two String arguments, and returns a String.

You can omit the curly braces { } of the function body and specify the body after = symbol if the function returns a single expression (like above example).

It is optional to explicitly declare the return type in such case because the return type can be inferred by the compiler. In the above example, you can replace

fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

with

fun getName(firstName: String, lastName: String) = "$firstName $lastName"

Kotlin for Loop

The for loop in Kotlin iterates through anything that provides an iterator. In this article, you learn to create for loop (with the help of examples).

There is no traditional for loop in Kotlin unlike Java and other languages.

In Kotlin, for loop is used to iterate through ranges, arrays, maps and so on (anything that provides an iterator).

The syntax of for loop in Kotlin is:

for (item in collection) {
    // body of loop
}

Example: Iterate Through a Range

fun main(args: Array<String>) {

    for (i in 1..5) {
        println(i)
    }
}

Here, the loop iterates through the range and prints individual item.

When you run the program, the output will be:

1
2
3
4
5

If the body of the loop contains only one statement (like above example), it’s not necessary to use curly braces { }.

fun main(args: Array<String>) {
    for (i in 1..5) println(i)
}

It’s possible to iterate through a range using for loop because ranges provides an iterator. To learn more, visit Kotlin iterators.


Example: Different Ways to Iterate Through a Range

fun main(args: Array<String>) {

    print("for (i in 1..5) print(i) = ")
    for (i in 1..5) print(i)

    println()

    print("for (i in 5..1) print(i) = ")
    for (i in 5..1) print(i)             // prints nothing

    println()

    print("for (i in 5 downTo 1) print(i) = ")
    for (i in 5 downTo 1) print(i)

    println()

    print("for (i in 1..4 step 2) print(i) = ")
    for (i in 1..5 step 2) print(i)

    println()

    print("for (i in 4 downTo 1 step 2) print(i) = ")
    for (i in 5 downTo 1 step 2) print(i)
}

When you run the program, the output will be:

for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) = 
for (i in 5 downTo 1) print(i) = 54321
for (i in 1..4 step 2) print(i) = 135
for (i in 4 downTo 1 step 2) print(i) = 531

Iterating Through an Array

Here’s an example to iterate through a String array.

fun main(args: Array<String>) {

    var language = arrayOf("Ruby", "Koltin", "Python" "Java")

    for (item in language)
        println(item)
}

When you run the program, the output will be:

Ruby
Koltin
Python
Java

It’s possible to iterate through an array with an index. For example,

fun main(args: Array<String>) {

    var language = arrayOf("Ruby", "Koltin", "Python", "Java")

    for (item in language.indices) {

        // printing array elements having even index only
        if (item%2 == 0)
            println(language[item])
    }
}

When you run the program, the output will be:

Ruby
Python

If you want to learn more about arrays, visit Kotlin arrays.


Iterating Through a String

fun main(args: Array<String>) {

    var text= "Kotlin"

    for (letter in text) {
        println(letter)
    }
}

When you run the program, the output will be:

K
o
t
l
i
n

Similar like arrays, you can iterate through a String with an index. For example,

fun main(args: Array<String>) {

    var text= "Kotlin"

    for (item in text.indices) {
        println(text[item])
    }
}

When you run the program, the output will be:

K
o
t
l
i
n

You will learn to iterate over a map using for loop in Kotin map article.

Kotlin while and do…while Loop

Loop is used in programming to repeat a specific block of code. In this article, you will learn to create while and do…while loops in Kotlin programming.

Loop is used in programming to repeat a specific block of code until certain condition is met (test expression is false).

Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times on your screen. Well, you can do it by using print statement 50 times (without using loops). How about you need to print a sentence one million times? You need to use loops.

You will learn about two loops while and do..while in this article with the help of examples.

If you are familiar with while and do…while loops in Java, you are already familiar with these loops in Kotlin as well.


Kotlin while Loop

The syntax of while loop is:

while (testExpression) {
    // codes inside body of while loop
}

How while loop works?

The test expression inside the parenthesis is a Boolean expression.

If the test expression is evaluated to true,

  • statements inside the while loop are executed.
  • then, the test expression is evaluated again.

This process goes on until the test expression is evaluated to false.

If the test expression is evaluated to false,

  • while loop is terminated.

Flowchart of while Loop

Kotlin while Loop Flowchart

Example: Kotlin while Loop

// Program to print line 5 times

fun main(args: Array<String>) {

    var i = 1

    while (i <= 5) {
        println("Line $i")
        ++i
    }
}

When you run the program, the output will be:

Line 1
Line 2
Line 3
Line 4
Line 5

Notice, ++i statement inside the while loop. After 5 iterations, variable i will be incremented to 6. Then, the test expression i <= 5 is evaluated to false and the loop terminates.


If the body of loop has only one statement, it’s not necessary to use curly braces { }


Example: Compute sum of Natural Numbers

// Program to compute the sum of natural numbers from 1 to 100.
fun main(args: Array<String>) {

    var sum = 0
    var i = 100

    while (i != 0) {
        sum += i     // sum = sum + i;
        --i
    }
    println("sum = $sum")
}

When you run the program, the output will be:

sum = 5050

Here, the variable sum is initialized to 0 and i is initialized to 100. In each iteration of while loop, variable sum is assigned sum + i, and the value of i is decreased by 1 until i is equal to 0. For better visualization,

1st iteration: sum = 0+100 = 100, i = 99
2nd iteration: sum = 100+99 = 199, i = 98
3rd iteration: sum = 199+98 = 297, i = 97
... .. ...
... .. ...
99th iteration: sum = 5047+2 = 5049, i = 1
100th iteration: sum = 5049+1 = 5050, i = 0 (then loop terminates)

To learn more about test expression and how it is evaluated, visit comparison and logical operators.


Kotlin do…while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed once before the test expression is checked.

Its syntax is:

do {
   // codes inside body of do while loop
} while (testExpression);

How do…while loop works?

The codes inside the body of do construct is executed once (without checking the testExpression). Then, the test expression is checked.

If the test expression is evaluated to true, codes inside the body of the loop are executed, and test expression is evaluated again. This process goes on until the test expression is evaluated to false.

When the test expression is evaluated to falsedo..while loop terminates.


Flowchart of do…while Loop

Kotlin do...while Loop flowchart

Example: Kotlin do…while Loop

The program below calculates the sum of numbers entered by the user until user enters 0.

To take input from the user, readline() function is used. 

fun main(args: Array<String>) {

    var sum: Int = 0
    var input: String

    do {
        print("Enter an integer: ")
        input = readLine()!!
        sum += input.toInt()

    } while (input != "0")

    println("sum = $sum")
}

When you run the program, the output will be something like:

Enter an integer: 4
Enter an integer: 3
Enter an integer: 2
Enter an integer: -6
Enter an integer: 0
sum = 3

Kotlin Expression, Statements and Blocks

In this article, you will learn about Kotlin expressions, Kotlin statements, difference between expression and statement, and Kotlin blocks.

Kotlin Expressions

Expressions consist of variables, operators etc that evaluates to a single value.

Let’s take an example,

val score: Int
score = 90 + 25

Here, 90 + 25 is an expression that returns Int value.


In Kotlin, if is an expression unlike Java (In Java, if is a statement). For example,

fun main(args: Array<String>) {

    val a = 12
    val b = 13
    val max: Int

    max = if (a > b) a else b
    println("$max")
}

Here, if (a > b) a else b is an expression. Then value of the expression is assigned to max variable in the above program. Visit this page to learn more about Kotlin if expression.


Kotlin Statements

Statements are everything that make up a complete unit of execution. For example,

val score = 90 + 25

Here, 90 + 25 is an expression that returns 115, and val score = 9*5; is a statement.

Expressions are part of statements.

Some examples:

println("Howdy")
var a = 5
++a
max = if (a > b) a else b

Kotlin Blocks

A block is a group of statements (zero or more) that is enclosed in curly braces { }. For example,

fun main(args: Array<String>) {  // main function block
    val flag = true

    if (flag == true) {      // start of if block
        print("Hey ")
        print("jude!")
    }                        // end of if block
}                            // end of main function block

There are two statements print("Hey ") and print(" jude!") inside if branch block.

print("Hey ")
print("jude!")

Similarly, the main() function also has a block body.

val flag = true

if (flag == true) {      // start of block
    print("Hey ")
    print("jude!")
}                        // end of block