Book Image

Hands-On Object-Oriented Programming with Kotlin

By : Abid Khan, Igor Kucherenko
Book Image

Hands-On Object-Oriented Programming with Kotlin

By: Abid Khan, Igor Kucherenko

Overview of this book

Kotlin is an object-oriented programming language. The book is based on the latest version of Kotlin. The book provides you with a thorough understanding of programming concepts, object-oriented programming techniques, and design patterns. It includes numerous examples, explanation of concepts and keynotes. Where possible, examples and programming exercises are included. The main purpose of the book is to provide a comprehensive coverage of Kotlin features such as classes, data classes, and inheritance. It also provides a good understanding of design pattern and how Kotlin syntax works with object-oriented techniques. You will also gain familiarity with syntax in this book by writing labeled for loop and when as an expression. An introduction to the advanced concepts such as sealed classes and package level functions and coroutines is provided and we will also learn how these concepts can make the software development easy. Supported libraries for serialization, regular expression and testing are also covered in this book. By the end of the book, you would have learnt building robust and maintainable software with object oriented design patterns in Kotlin.
Table of Contents (14 chapters)

Using the try block as an expression

When we run program code, we deal with expressions and statements all the time. It's very important to understand the difference between these. Let's look at the following code:

1 + 1

This code is an expression because it contains variables, operators, and returns a single result. If a standalone element of program code represents an action, it is a statement:

println("Hello")

In the context of this section, the main point for us is that an expression returns something. In Kotlin, the try { ... } catch { ... } finally { ... } block is an expression and we can write something like this:

fun loadValue(): Int = throw Exception()

fun main(args: Array<String>) {
println(try { loadValue() } catch (exception: Exception) { 4 })
}

Under the hood, this code works in the same way as if we were to write it in Java. To check this...