Kotlin Extension Methods Top-Level Extensions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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)


Got any Kotlin Question?