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

Making asynchronicity explicit

As you saw in the previous chapter, it is very easy to create an asynchronous function in Kotlin. Here is an example:

fun CoroutineScope.getResult() = async { 
   delay(100) 
   "OK" 
}

However, this asynchronicity may be an unexpected behavior for the user of the function, as they may expect a simple value.

What do you think the following code prints?

println("${getResult()}")

For the user, the preceding code somewhat unexpectedly prints the following instead of "OK":

> Name: DeferredCoroutine{Active}@...

Of course, if you have read Chapter 6, Threads and Coroutines, you will know that what's missing here is the await() function:

println("${getResult().await()}")

But it would have been a lot more obvious if we'd named our function accordingly, by adding an async suffix:

fun CoroutineScope.getResultAsync() = async { 
   delay...
lock icon The rest of the chapter is locked
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 $19.99/month. Cancel anytime