What are extended functions?

Asked

Viewed 257 times

10

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

  • 3

    Out of curiosity, what kind of article are you writing?

  • It is a scientific article for a college subject, it is not very elaborate, it is up to 4 pages

1 answer

10


I assume you’re talking about Extension Functions or extension functions.

They are used to extend functionality in an existing type.

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

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

According to the documentation if you want to make a method that can be used in any MutableList of a Int exchanging data from 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 (she has companion objects that are essentially the same thing) it would be the same as calling

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

I put in the Github for future reference.

in this case the l would be passed as argument for the function and this parameter would be accessed with this.

C# had something similar.

  • When you do Mutablelist<Int>. swap(l, 0, 2) you are passing 3 parameters and in the swap function declaration you expect 2 (index1,index2) . How does he know that the first parameter is the list on which I will make?

  • @L.J I didn’t say it works, I said it’s the same as doing it in a normal static method (well Kotlin doesn’t use that terminology).

  • Oh yes, I understood that this would work: Mutablelist<Int>. swap(l, 0, 2) Thank goodness I asked...rsrs. When you say :(good Kotlin does not use this terminology) is saying that Kotlin has no static methods or possesses with other terminology?

  • @L.J only other terminology, but it’s the same thing, the tb extension is a static method with different syntax.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.