Book Image

Kotlin Design Patterns and Best Practices - Second Edition

By : Alexey Soshin
Book Image

Kotlin Design Patterns and Best Practices - Second Edition

By: Alexey Soshin

Overview of this book

This book shows you how easy it can be to implement traditional design patterns in the modern multi-paradigm Kotlin programming language, and takes you through the new patterns and paradigms that have emerged. This second edition is updated to cover the changes introduced from Kotlin 1.2 up to 1.5 and focuses more on the idiomatic usage of coroutines, which have become a stable language feature. You'll begin by learning about the practical aspects of smarter coding in Kotlin, as well as understanding basic Kotlin syntax and the impact of design patterns on your code. The book also provides an in-depth explanation of the classical design patterns, such as Creational, Structural, and Behavioral families, before moving on to functional programming. You'll go through reactive and concurrent patterns, and finally, get to grips with coroutines and structured concurrency to write performant, extensible, and maintainable code. By the end of this Kotlin book, you'll have explored the latest trends in architecture and design patterns for microservices. You’ll also understand the tradeoffs when choosing between different architectures and make informed decisions.
Table of Contents (17 chapters)
1
Section 1: Classical Patterns
6
Section 2: Reactive and Concurrent Patterns
11
Section 3: Practical Application of Design Patterns

Reified generics

Previously in this chapter, we mentioned inline functions. Since inline functions are copied, we can get rid of one of the major JVM limitations: type erasure. After all, inside the function, we know exactly what type we're getting.

Let's look at the following example. We would like to create a generic function that will receive a Number (Number can either be Int or Long), but will only print it if it's of the same type as the function type.

We'll start with a naïve implementation, simply trying the instance check on the type directly:

fun <T> printIfSameType(a: Number) { 
    if (a is T) { // <== Error 
        println(a)    
    } 
}

However, this code won't compile and we'll get the following error:

> Cannot check for instance of erased type: T

What we usually do in Java, in this case, is pass the class...