Reader small image

You're reading from  Kotlin Design Patterns and Best Practices - Third Edition

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781805127765
Edition3rd Edition
Right arrow
Author (1)
Alexey Soshin
Alexey Soshin
author image
Alexey Soshin

Alexey Soshin is a software architect with 18 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design
Read more about Alexey Soshin

Right arrow

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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Kotlin Design Patterns and Best Practices - Third Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127765

Author (1)

author image
Alexey Soshin

Alexey Soshin is a software architect with 18 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design
Read more about Alexey Soshin