Kotlin Top-Level Extensions


Example

Top-level extension methods are not contained within a class.

fun IntArray.addTo(dest: IntArray) {
    for (i in 0 .. size - 1) {
        dest[i] += this[i]
    }
}

Above an extension method is defined for the type IntArray. Note that the object for which the extension method is defined (called the receiver) is accessed using the keyword this.

This extension can be called like so:

val myArray = intArrayOf(1, 2, 3)
intArrayOf(4, 5, 6).addTo(myArray)