Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kotlin Design Patterns and Best Practices

You're reading from   Kotlin Design Patterns and Best Practices Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin

Arrow left icon
Product type Paperback
Published in Jan 2022
Publisher Packt
ISBN-13 9781801815727
Length 356 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Alexey Soshin Alexey Soshin
Author Profile Icon Alexey Soshin
Alexey Soshin
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Section 1: Classical Patterns
2. Chapter 1: Getting Started with Kotlin FREE CHAPTER 3. Chapter 2: Working with Creational Patterns 4. Chapter 3: Understanding Structural Patterns 5. Chapter 4: Getting Familiar with Behavioral Patterns 6. Section 2: Reactive and Concurrent Patterns
7. Chapter 5: Introducing Functional Programming 8. Chapter 6: Threads and Coroutines 9. Chapter 7: Controlling the Data Flow 10. Chapter 8: Designing for Concurrency 11. Section 3: Practical Application of Design Patterns
12. Chapter 9: Idioms and Anti-Patterns 13. Chapter 10: Concurrent Microservices with Ktor 14. Chapter 11: Reactive Microservices with Vert.x 15. Assessments 16. Other Books You May Enjoy

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. For example, you would 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)
}

This solution is quite wasteful, though. 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 almost like a regular top-level function declaration, but with one crucial change – before the function name comes a class name. That class is called a method receiver.

Inside the function body, this will refer to any String class that the function was invoked on.

Now, let's declare a regular string and try to invoke this new function on it:

val password: String = "secretpassword"
println("Password: ${password.hidePassword()}")

This prints the following:

> Password: **************

What black magic is this? We managed to add a function to a final class, something that technically should be impossible.

This is another feature of the Kotlin compiler, one among many. This extension function will be compiled to the following code:

// This is not real Kotlin
fun hidePassword(this: String) {
    "*".repeat(this.length)
}

You can see that, in fact, this is a regular top-level function. Its first argument is an instance of the class that we extend. This also might remind you of how methods on structs in Go work.

The code that prints the masked password will be adapted accordingly:

val password: String = "secretpassword"
println("Password: ${hidePassword(password)}")

For that reason, the extension functions cannot override the member function of the class, or access its private or protected properties.

You have been reading a chapter from
Kotlin Design Patterns and Best Practices - Second Edition
Published in: Jan 2022
Publisher: Packt
ISBN-13: 9781801815727
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime