Extension functions
The last feature we’ll cover in this chapter, before moving on, is extension functions. Sometimes, you may want to extend the functionality of a class that is declared final or is not under your control. For example, you might like to have a string that has the hidePassword()
function from the previous section.
One way to achieve that is to declare a class that wraps the string for us:
data class Password(val password: String) {
fun hidePassword() = "*".repeat(password.length)
}
However, this solution is somewhat inefficient, as it adds another level of indirection.
In Kotlin, there’s a better way to implement this. To extend a class without inheriting from it, we can prefix the function name with the name of the class we’d like to extend:
fun String.hidePassword() = "*".repeat(this.length)
This looks similar to a regular top-level function declaration, but with one crucial change – before...