Skip to content
Extension function is a magic

Extension function is a magic

1 min read #kotlin

This is one of my most favorite features of Kotlin - Extension Function. Imagine this. You are using a 3rd party library - String that have all the things that I would need for text manipulation- almost. If I have another one or two functions under String topic, Extension Function would solve this problem beautifully.

Kotlin’s extension functions effectively add member functions to existing class.

fun String.addGreetingEmoji() = "Hi $this 👋"
"Dave".addGreetingEmoji() // Hi Dave 👋
kotlin

You can also apply extension function to your own class.

class Team(public val name: String)

fun Team.intro(noOfPeople: Int) = "$name team has $noOfPeople."

fun main() {
  val team = Team("Man Utd")
  println(team.intro(11)) //Man Utd team has 11.
}
kotlin

Note that the extension function Team.intro can access to name in Team class. If the name is private, the extension function couldn’t access from the extension function.

For extension function, you can rewrite Team.intro(Int) into intro(Team, Int). The only reason for using extension function is the syntax. This is called syntax sugar, which is cleaner and more powerful.