What are extended functions?


I'm writing an article on programming in Kotlin, I came across this name, what are extended functions?

asked by anonymous 25.10.2017 / 19:58

1 answer


I imagine you're talking about Extension Functions or extension functions.

They are used to extend functionality into an existing type.

You write them as normal functions and it works as if it were a function of the type, that is, as if it were a method that type has.

The this can be used as a normal method to access the object being manipulated. But there are limitations of what you can access in it. Only public members can be accessed since the role is external and does not have extra access privileges.

According to the documentation if you want to make a method that can be used in any% of% of a MutableList that exchanges data of two indexes would do so:

fun MutableList<Int>.swap(index1: Int, index2: Int) {
    val tmp = this[index1] // 'this' corresponds to the list
    this[index1] = this[index2]
    this[index2] = tmp

So it could be used this way:

val l = mutableListOf(1, 2, 3)
l.swap(0, 2)

If Kotlin had normal static methods (it has company objects that are essentially the same thing) would be the same as calling

MutableList<Int>.swap(l, 0, 2)

In this case the Int would be passed as argument to the function and this parameter would be accessed with l .

C # already had something like that .

25.10.2017 / 20:08