Kotlin Extension Operators

Kotlin allows classes to be extended using Extension Functions. These Extension Functions can also be used for extending operators if they are declared with the `operator` keyword.

An example of such an Extension Function can be seen below, to draw a repeated set of characters.

operator fun Int.times(text: CharSequence): CharSequence {
    val result = StringBuilder()

    for (i in 1..this) {
        result.append(text)
    }

    return result.toString()
}

fun main(args: Array<String>) {
    val line = 10 * "x"

    println(line)
}

Running the script results in the output of a line consisting of x characters:

xxxxxxxxxx

2 Replies to “Kotlin Extension Operators”

  1. You could add example with “buildString” tip in this example 😉

    operator fun Int.times(text: CharSequence): CharSequence {
        return buildString {
            for (i in 1..this@times) {
                append(text)
            }
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *