Book Image

Android Development with Kotlin

By : Igor Wojda, Marcin Moskala
Book Image

Android Development with Kotlin

By: Igor Wojda, Marcin Moskala

Overview of this book

Nowadays, improved application development does not just mean building better performing applications. It has become crucial to find improved ways of writing code. Kotlin is a language that helps developers build amazing Android applications easily and effectively. This book discusses Kotlin features in context of Android development. It demonstrates how common examples that are typical for Android development, can be simplified using Kotlin. It also shows all the benefits, improvements and new possibilities provided by this language. The book is divided in three modules that show the power of Kotlin and teach you how to use it properly. Each module present features in different levels of advancement. The first module covers Kotlin basics. This module will lay a firm foundation for the rest of the chapters so you are able to read and understand most of the Kotlin code. The next module dives deeper into the building blocks of Kotlin, such as functions, classes, and function types. You will learn how Kotlin brings many improvements to the table by improving common Java concepts and decreasing code verbosity. The last module presents features that are not present in Java. You will learn how certain tasks can be achieved in simpler ways thanks to Kotlin. Through the book, you will learn how to use Kotlin for Android development. You will get to know and understand most important Kotlin features, and how they can be used. You will be ready to start your own adventure with Android development with Kotlin.
Table of Contents (16 chapters)
Title Page
About the Authors
About the Reviewers
Customer Feedback
Making Your Marvel Gallery Application

Tail-recursive functions

Recursive functions are functions that call themselves. Let's see an example of a recursive function, getState:

    fun getState(state: State, n: Int): State = 
        if (n <= 0) state // 1 
        else getState(nextState(state), n - 1)

They are an important part of the functional programming style, but the problem is that each recursive function call needs to keep the return address of the previous function on the stack. When an application recurses too deeply (there are too many functions on the stack), StackOverflowError is thrown. This limitation presents a very serious problem for recurrence usage.

A classic solution for this problem was to use iteration instead of recurrence, but this approach is less expressive:

    fun getState(state: State, n: Int): State { 
        var state = state 
        for (i in 1..n) { 
            state = state.nextState() 
        return state 

A proper solution for this problem is usage of the tail-recursive...