Search⌘ K
AI Features

Extension Functions

Explore Kotlin extension functions and how they enable adding functionality to final classes without inheritance. Learn the syntax using method receivers and see practical examples with String to hide passwords. Understand the limitations of extension functions compared to class members.

We'll cover the following...

Sometimes, we want to extend the functionality of a class that is declared final. For example, to have a string that has the hidePassword() function.

One way to achieve that is to declare a class that wraps the string for us:

Kotlin 1.5
data class Password(val password: String) {
fun hidePassword() = "*".repeat(password.length)
}

This solution is quite wasteful, though. It adds another level of indirection.

In Kotlin, there’s a better way to ...