Book Image

Hands-On Design Patterns with Kotlin

By : Alexey Soshin
Book Image

Hands-On Design Patterns with Kotlin

By: Alexey Soshin

Overview of this book

Design patterns enable you as a developer to speed up the development process by providing you with proven development paradigms. Reusing design patterns helps prevent complex issues that can cause major problems, improves your code base, promotes code reuse, and makes an architecture more robust. The mission of this book is to ease the adoption of design patterns in Kotlin and provide good practices for programmers. The book begins by showing you the practical aspects of smarter coding in Kotlin, explaining the basic Kotlin syntax and the impact of design patterns. From there, the book provides an in-depth explanation of the classical design patterns of creational, structural, and behavioral families, before heading into functional programming. It then takes you through reactive and concurrent patterns, teaching you about using streams, threads, and coroutines to write better code along the way By the end of the book, you will be able to efficiently address common problems faced while developing applications and be comfortable working on scalable and maintainable projects of any size.
Table of Contents (13 chapters)

Deferred value

We've already met deferred values in Chapter 8, Threads and Coroutines, in the Returning results section. Deferred is the result of the async() function, for example. You may also know them as Futures from Java or Scala, or as Promises from JavaScript.

Interestingly enough, Deferred is a Proxy design pattern that we've met in previous chapters.

Much as the Kotlin Sequence is very similar to the Java8 Stream, Kotlin Deferred is very similar to Java Future. You'll rarely need to create your own Deferred. Usually, you would work with the one returned from async().

In cases where you do need to return a placeholder for a value that would be evaluated in the future, you can do it:

val deferred = CompletableDeferred<String>()

launch {
delay(100)
if (Random().nextBoolean()) {
deferred.complete("OK")
}
else {
deferred...