Kotlin Extension Function

In this article, you will learn to extend a class with new functionality using extension functions.

Suppose, you need to extend a class with new functionality. In most programming languages, you either derive a new class or use some kind of design pattern to do this.

However, in Koltin, you can also use extension function to extend a class with new functionality. Basically, an extension function is a member function of a class that is defined outside the class.

For example, you need to use a method to the String class that returns a new string with first and last character removed; this method is not already available in String class. You can use extension function to accomplish this task.


Example: Remove First and Last Character of String

fun String.removeFirstLastChar(): String =  this.substring(1, this.length - 1)

fun main(args: Array<String>) {
    val myString= "Hello Everyone"
    val result = myString.removeFirstLastChar()
    println("First character is: $result")
}

When you run the program, the output will be:

First character is: ello Everyon

Here, an extension function removeFirstLastChar() is added to the String class.

The class name is the receiver type (String class in our example). The this keyword inside the extension function refers the receiver object.

Kotlin extension function receiver type and obejct

If you need to integrate Kotlin on the top of Java project, you do not need to modify the whole code to Koltin. Just use extension functions to add functionalities.

Kotlin break Expression

In this tutorial, you will learn to use break to terminate a loop. Also, you will also learn about break labels.

Suppose you are working with loops. It is sometimes desirable to terminate the loop immediately without checking the test expression.

In such case, break is used. It terminates the nearest enclosing loop when encountered (without checking the test expression). This is similar to how break statement works in Java.


How break works?

It is almost always used with if..else construct. For example,

for (...) {
    if (testExpression) {
        break
    }
}

If testExpression is evaluated to truebreak is executed which terminates the for loop.


Example: Kotlin break

fun main(args: Array<String>) {

    for (i in 1..10) {
        if (i == 5) {
            break
        }
        println(i)
    }
}

When you run the program, the output will be:

1
2
3
4

When the value of i is equal to 5, expression i == 5 inside if is evaluated to true, and break is executed. This terminates the for loop.


Example: Calculate Sum Until User enters 0

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

Visit Kotlin Basic Input Output to learn more on how to take input from the user.

fun main(args: Array<String>) {

    var sum = 0
    var number: Int

    while (true) {
        print("Enter a number: ")
        number = readLine()!!.toInt()

        if (number == 0)
            break

        sum += number
    }

    print("sum = $sum")
}

When you run the program, the output will be:

Enter a number: 4
Enter a number: 12
Enter a number: 6
Enter a number: -9
Enter a number: 0
sum = 13

In the above program, the test expression of the while loop is always true.

Here, the while loop runs until user enters 0. When user inputs 0, break is executed which terminates the while loop.


Kotlin Labeled break

What you have learned till now is unlabeled form of break, which terminates the nearest enclosing loop. There is another way break can be used (labeled form) to terminate the desired loop (can be outer loop).


How labeled break works?

Label in Kotlin starts with an identifier which is followed by @.

Here, test@ is a label marked at the outer while loop. Now, by using break with a label (break@test in this case), you can break the specific loop.

Here’s an example:

fun main(args: Array<String>) {

    first@ for (i in 1..4) {

        second@ for (j in 1..2) {
            println("i = $i; j = $j")

            if (i == 2)
                break@first
        }
    }
}

When you run the program, the output will be:

i = 1; j = 1
i = 1; j = 2
i = 2; j = 1

Here, when i == 2 expression is evaluated to truebreak@first is executed which terminates the loop marked with label first@.


Here’s a little variation of the above program.

In the program below, break terminates the loop marked with label @second.

fun main(args: Array<String>) {

    first@ for (i in 1..4) {

        second@ for (j in 1..2) {
            println("i = $i; j = $j")

            if (i == 2)
                break@second
        }
    }
}

When you run the program, the output will be:

i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
i = 3; j = 1
i = 3; j = 2
i = 4; j = 1
i = 4; j = 2

Note: Since, break is used to terminate the innermost loop in this program, it is not necessary to use labeled break in this case.


There are 3 structural jump expressions in Kotlin: breakcontinue and return.