40,81 €
Learn everything you need to know about object-oriented programming with the latest features of Kotlin 1.3
Key Features
Book Description
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.
What you will learn
Who this book is for
This book is for programmers and developers who wish to learn Object-oriented programming principles and apply them to build robust and scalable applications. Basic knowledge in Kotlin programming is assumed
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 366
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa TripathiAcquisition Editor: Sandeep MishraContent Development Editor: Manjusha MantriTechnical Editor: Abhishek SharmaCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Mariammal ChettiyarGraphics: Jisha ChirayilProduction Coordinator: Deepika Naik
First published: October 2018
Production reference: 1311018
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78961-772-6
www.pack.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals
Improve your learning with skill plans designed especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and, as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Abid Khan is an application developer and test engineer with over 10 years of experience. He has worked with different programming languages, including C/C++ and Java, and he now works with Kotlin as a primary language for Android development. Abid lives in Stockholm, Sweden. He spends his time to learn new technologies and then writes about it.
Igor Kucherenko is an Android developer at Techery, a software development company that uses Kotlin as the main language for Android development. Currently, he lives in Ukraine, where he is a speaker in the Kotlin Dnipro Community, which promotes Kotlin and shares knowledge with audiences at meetups. You can find his articles about Kotlin and Android development on Medium and a blog for Yalantis, where he worked previously.
Hardik Trivedi is a self-taught computer programmer. He has been extensively working on Android and Java since 2010 and has also immersed himself in Kotlin and JavaScript. When he is not working on client projects, he loves contributing back to the development community by spending time on Stack Overflow and writing tech blogs. He has also coauthored two books on Kotlin, named Kotlin Blueprints and Hands-On Serverless Applications with Kotlin. Hardik also mentors college students, professionals, and companies who have a keen interest in mobile app development. He is also an active community speaker. Someday in the future, you may find him owning a restaurant and serving exquisite cuisines to his customers.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Object-Oriented Programming with Kotlin
Dedication
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with Kotlin
Technical requirements
Introduction to Kotlin
Data types in Kotlin
Declaring a variable in Kotlin
The var keyword
The val keyword
Type inference
Type annotation
Number data types
Real data types
Boolean data type
Character data type
Type checking with the is keyword
String variable
Null safety, type casting, Pair, and Triple
Null safety
Safe call operators 
The ?.  Safe call operator  
The ?: Elvis operator
The !! Sure operator
Type casting
Converting from Byte to Float
Converting from Double to Integer
Converting from String to Integer
Smart cast
Unsafe cast
Pair and Triple 
How to declare
How to retrieve values
Flow controls
The if statement
The if and else statements
The if statement with a conditional operator
The if statement with the and (&&) operator
The if statement with the or (||) operator
The if statement with the (!) Not operator
if as an expression
The When expression
Combining cases
Ranges with When
When as an expression
Introduction to loops 
The while loop
Defining the while loop
The do while loop  
The for loop
 Defining the for loop 
The nested for loop
Break statements
The break statement with labeled for loop 
What is a function?
Function declaration
Functions with no parameter and no return type
Function with parameters
Functions with parameters and return types
Function as an expression
Functions with default arguments
Functions with named parameters
Functions and vararg
vararg with other arguments
Package-level functions
How to access a function
Summary
Questions
Further reading
Introduction to Object-Oriented Programming
Technical requirements
Object-oriented programming?
Classes and objects
Attributes and behaviors
Benefits of object-oriented programming
Classes in Kotlin
Properties – first-class citizens
Constructing a class with a constructor
Default constructor
Primary constructor
Primary constructor with the init block
The this keyword 
Secondary constructor
Constructor overloading
Constructor with default parameters
Constructor with named parameters
What are data classes?
The toString() function
The copy function
The hashCode() function
Object decomposition
Classes and functions
Function overloading
Summary
Questions
Further reading
The Four Pillars of Object-Oriented Programming
Technical requirements
Encapsulation
Information-hiding
Visibility modifier 
The private modifier
The protected modifier
Implementation-hiding
What is inheritance?
Using the open keyword
Using the super keyword
Class-initialization hierarchy
Abstraction
Abstract classes
Abstract functions
Interfaces
Multiple interfaces
Resolving conflicts between interfaces
Interfaces and polymorphism
Overriding
What is overriding?
The super keyword
The final keyword
Rules for function-overriding
Property-overriding 
Types of inheritance
Single inheritance
Multilevel inheritance
Hierarchical inheritance
Hierarchical multilevel inheritance
The is-a relationship
Polymorphism
How polymorphism works
Dynamic binding
Summary
Questions
Further reading
Classes - Advanced Concepts
Technical requirements
Sealed classes and enumeration
Sealed classes
Sealed classes with the when block
Why do we need sealed classes?  
Enum classes
The enum class with a constructor
The enum class and functions
The enum class and interfaces
Objects and companion objects
The object class with inheritance and interfaces
Companion objects
Companion functions and interfaces
Aggregation, composition, and nested classes
Aggregation
Composition
Nested classes
Inner classes
Class properties
Delegate properties
Built-in delegates
Summary
Questions
Further reading
Data Collection, Iterators, and Filters
Technical requirements
Range
Types of ranges
Declaring a range
The rangeTo function 
The until function
The downTo function
The step function
The contains function
The elementAt function
Range properties
The coerce functions
The coerceIn function
The coerceAtMost(maxValue) function
The coerceAtLeast(minValue) function
Arrays 
Defining arrays
Arrays of a specific type
Index of the array element
The get function
The array and for loop
Array declaration and initialization
The set function
Mutable arrays with immutable elements
Arrays with lambda expressions
Arrays of different elements
The arrayOfNulls function
Copying arrays
Lists in Kotlin
Immutable lists
The listOfNotNull function
List access
Immutable lists and interfaces
Iterable interfaces
Collection interfaces
List interfaces
Mutable lists
The MutableIterable interface
Mutable collection interfaces
Mutable list interfaces
Sets in Kotlin 
Immutable sets
Mutable sets
Map
Immutable maps
Mutable maps
Iterators in Kotlin
Iterators
List iterators
Mutable iterators
Mutable list iterators
Filters and collection functions
The filter function  
The it keyword 
The filterNot function
The filterNotNull function
The filterIsInstance<dataType> function
The slice function
The take function
takeLast
takeWhile
takeLastWhile
The drop function
dropLast
dropWhile
dropWhileLast
The fold function
foldRight 
The reduce function
reduceRight
reduceRightIndexed
Some important functions
foreach
forEachIndexed
onEach
max and maxBy
min and minBy
Summary
Questions
Further reading
Object-Oriented Patterns in Kotlin
Technical requirements
What design patterns are and how they help
Types of design patterns
Creational patterns
Structural patterns
Behavioral patterns
Creational patterns
Builder
Factory method
Abstract factory
Singleton
Structural patterns
Adapter
Decorator
Facade
Proxy
Behavioral patterns
Observer
Strategy
Command 
State
Chain of responsibility
Visitor
Summary
Coroutines - a Lightweight Thread?
Technical requirements
What are coroutines?
Coroutines and threads
Coroutine examples
Exception handling
Resource releasing
Non-cancelable block
Parallel execution
Lazy execution
Channels
Summary
Interoperability
Technical requirements
Calling Java code in Kotlin
Calling static variables and functions
Calling the Java collection in Kotlin
Reserve words in Kotlin  
Java classes in Kotlin 
Calling Kotlin code in Java
Calling the Kotlin function 
Extension functions
Functions with mutable collections
Functions with immutable collections
Functions with the JVM annotation
Calling the Kotlin class
Calling the Kotlin singleton class
Summary
Questions
Further reading
Regular Expression and Serialization in Kotlin
Technical requirements
Introducing regular expression
Kotlin and regular expression
Introducing serialization
Serialization and Kotlin support
Summary
Exception Handling
Technical requirements
What is exception handling?
Checked and unchecked exceptions
 Exception hierarchy
Exceptions in Java
Exceptions in Kotlin
Interoperability
Using the try block as an expression
Writing your own exception
Summary
Questions
Further reading
Testing in Object-Oriented Programming with Kotlin
Technical requirements
Why testing?
Types of testing
Manual testing
Automated testing
Unit testing
The Kotlin test libraries
Installation
Gradle with Groovy
Gradle with the Kotlin script
Maven
Testing examples
Class references
Writing specifications
The given, on, and it blocks
Testing exceptions
The describe and it blocks
Summary
Questions
Further reading
Assessments
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 8
Chapter 10
Chapter 11
Other Books You May Enjoy
Leave a review - let other readers know what you think
Kotlin is a statically typed programming language that is designed to interoperate with Java code. Since the kotlinc compiler generates the same bytecode as javac, migrating to a new code base doesn't require a lot of effort. Kotlin is a modern language that contains many features from different paradigms that allow you to write concise and safe code. In light of all these points, Kotlin is growing in popularity and seeing an increase in the number of developers who use it.
This book is intended for developers who would like to gain a deeper understanding of how Kotlin works under the hood. The material doesn't depend on a certain platform or framework, but it focuses on Java Virtual Machine. This book doesn't cover topics about Kotlin to JavaScript and Kotlin/Native features. It's a good choice for client-side developers because it contains examples involving user interfaces and multithreaded environments.
Chapter 1, Getting Started with Kotlin, provides a brief overview of the Kotlin programming language. This chapter also covers data types and how null safety and type casting works. It also provides an introduction to operators and flow controls. At the end of this chapter, we will look at loops and functions.
Chapter 2, Introduction to Object-Oriented Programming, discusses what object-oriented programming is and why it is different and better than procedural programming. This chapter explains classes and data classes in Kotlin, and how Kotlin makes them unique. It also discusses in detail constructors, types of constructors, and properties, and what is meant by properties as first class citizens.
Chapter 3, The Four Pillars of Object-Oriented Programming, provides a thorough description of four pillars of object-oriented programming. It also explains what encapsulation is and how inheritance works. We also look into topics such as why choose polymorphism and what the benefits of abstraction are. Finally, we will learn how to declare a parent class and how to utilize resources in child class. In addition to defining derived classes, this chapter discusses how variables and functions can be redefined in child class, explicit type casting, and implicit type conversion within class hierarchies.
Chapter 4, Classes – Advanced Concepts, describes the key concepts of programming that are provided exclusively by Kotlin. This chapter discusses the concepts of sealed classes, object and companion objects, and why they are different from traditional classes. It also explains properties and delegates in classes.
Chapter 5, Data Collection, Iterators, and Filters, describes the handling of data collection by using different data structures provided in Kotlin. We also learn how to define and use arrays and how to utilize different templates for the efficient management of object collections such as lists, sets, collections, and maps. Besides discussing different data collection techniques, this chapter explains the power of interfaces used in collection classes. You will learn what an iterator is, how iterators are used with different collections, and the issues you may encounter while using it. This chapter also explains what filters are, how filters work, and how to ignore irrelevant data. At the end, this chapter elaborates on how to write your own filters.
Chapter 6, Object-Oriented Patterns in Kotlin, deals with the advanced concepts of object-oriented programming referred to as design patterns. Design patterns are a general solution to a known problem in software design. Design patterns can speed up development processes and reduce the risk of design errors that may occur at a later stage. Different design patterns are used for different problems; this chapter discusses software design challenges and design patterns. Each design pattern is subdivided into different categories that will be discussed in further detail.
Chapter 7, Coroutine – a Lightweight Thread?, describes how Kotlin has introduced a new library called coroutine. Coroutines can be considered a lightweight thread that do not push CPU to its limits, even when thousands of requests are in progress. This chapter explains what a coroutine is, and why it is superior to traditional threads in Java.
Chapter 8, Interoperability, discusses the fact that Kotlin is a superset of Java that is designed with Java interoperability in mind. Interoperability means you can call Java functions in Kotlin, and vice versa, and you can have both Java and Kotlin files in the same application. This chapter discusses in detail the technology behind interoperability and how to write cross-platform code. Most importantly, it also explains how to handle nullable calls that may appear from Java.
Chapter 9, Regular Expression and Serialization in Kotlin, describes how regular expressions, also known as regex, are a combination of different characters that helps to find and locate the necessary information from a huge amount of text. This technique is also called pattern matching, where users provide a string (pattern) and get a list of exact or similar matches. All advanced text editors use regular expressions to find the variable in your code. In this chapter, you will see that Kotlin has provided complete support for regular expressions and how they support writing bug-free patterns. This chapter also discusses serialization and how Kotlin works with text formats such as JSON.
Chapter 10, Exception Handling, discusses exceptions and exception handling in detail. We also learn about what the different keywords are try, catch, throw finally, and more, the different types of exceptions, and how a user can create user-defined exceptions and handle them. This chapter also explains how to prepare test environments to be able to write some tests.
Chapter 11, Testing in Object-Oriented Programming with Kotlin, provides an insight into the importance of testing, why testing is required, and the repercussions if code is released without testing. This chapter also explains the testing techniques, the dedicated Kotlin library for testing, and how Kotlin can help to write clean and readable test cases.
To run examples from this book, you will need a computer running Windows, Linux, or macOS. You will also need IntelliJ IDEA (the Ultimate edition version is preferable), and Android Studio. You will need a basic knowledge of GitHub and Git to clone a project with examples.
Since Kotlin is an official language of Android development, Android Studio supports this language out of the box. For IntelliJ IDEA, you need to install a plugin that is available for download from https://plugins.jetbrains.com/plugin/6954-kotlin.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Object-Oriented-Programming-with-Kotlin. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Kotlin's popularity has skyrocketed in recent months due to the fact that it is a simple and concise language that is easy to learn and supports object-oriented and functional programming. Kotlin is a superset of Java that avoids all unwanted Java features, such as verbose, unsafe, and outdated syntax, and includes powerful features from different languages. These features include security, simplicity, and interoperability.
This chapter enables us to acquire knowledge about Kotlin and introduces its basic features and functionality, aiming to get us started as quickly as possible. Before reaching the end of this chapter, we will be familiar with Kotlin's syntax, simplicity, and security features, as well as Kotlin's underlying approach towards object-oriented programming.
The following topics will be covered in this chapter:
Kotlin's history
Data types and ease of declaration
Kotlin's null safety and type casting
Flow control and
if
statements as an expression
Loops and labeled loops
Functions, functions as an expression, and named parameters
IntelliJ IDEA is used as a development environment, either Community or Ultimate Edition. This can be downloaded here: www.jetbrains.com/idea/download.
Make sure that the latest Java Development Kit (JDK) is installed and configured in our system. Download the JDK here: www.oracle.com/technetwork/java/javase/downloads/index.html.
The code for this chapter can be downloaded here: https://github.com/PacktPublishing/Hands-On-Object-Oriented-Programming-with-Kotlin/tree/master/src/main/kotlin/Chapter01.
In 2010, Jet Brains started working on a project called Project Kotlin. This aimed to develop a language that is easy, concise, and expressive. This is also a language that can help to improve productivity without compromising on quality, including that of backward compatibility and interoperability with existing code bases. Other than freedom from semicolons, there are a number of reasons to use Kotlin.
For a start, a beginner programmer can feel as comfortable as an experienced developer when using it. It also compiles to Java-6 bytecode, which allows a developer to use advanced features such as lambda expressions with legacy code. Kotlin is 100% interoperable with Java, so it is possible to call Kotlin code in Java as well as calling Java code in Kotlin. Furthermore, it is concise and expressive, and it helps avoid the boilerplate code that is required in Java. Kotlin is safe, therefore most Null Pointer Exceptions (NPEs) can be avoided. By default, it is not allowed to assign null values to variables. If the type of the variable is verified at compile time, the language is considered to be statically typed. Kotlin is a statically typed language and the benefit of this is that all tricky and trivial bugs can be caught at an early stage. With dynamically typed languages, type checking is performed at runtime. Perl, Smalltalk, and Ruby belong to a dynamically typed language group. Kotlin has great tooling support because it is a product of Jet Brains, a company renowned for providing IDEs for development. In addition, Kotlin supports Android because it is officially supported by Google. Kotlin supports Kotlin/Native technology for compiling Kotlin code in native binaries which does not rely on virtual machine and Kotlin supports browsers because all modern languages should work with JavaScript. A number of big brands (including Pinterest, Uber, Gradle, and Evernote) have started using Kotlin as a main language, and they feel that it helps to improve their productivity and quality of code.
With the help of Kotlin, we will now create our first hello world application as follows:
Start IntelliJ IDE and click on
File
.
Click on the
New
option and then click on the
Project
in the
Menu
.
From the left pane in the newly opened window, select
Kotlin
|
Kotlin/JVM
and then press
Next
.
Assign a project name and location, making sure that the latest SDK is selected.
Click on
Finish
.
IntelliJ IDE will open a new window with preconfigured files and folders.
src
is a source folder where all Kotlin files will be added.
Right-click on
src
and select
New
. Under this, click on
Kotlin File/Class
.
Assign a name, select a file from the
Kind
menu, and press
OK
.
Add the following code in the newly opened window:
fun main(args: Array<String>) { println("Hello world") }
In the same way as any other modern language, Kotlin uses variables or data types, which are among the most important features in programming. These variables are created to handle different types of data, including numbers, letters, words, and so on. Variables are allocated locations in memory for storing all kinds of data.
The data types in Kotlin are as follows:
Byte
Short
Integer
Long
Float
Double
Character
Boolean
There are two keywords available in Kotlin—varandval. Thevarkeyword declares a mutable data type and thevalkeyword declares an immutable or read-only variable.
Type inference is one of the most powerful features in Kotlin, but sometimes it becomes hazardous when the type of variable is unknown. For example, we are asked to write a function that can take variable of the Any type. This can be float, string, or int:
fun func(x: Any) { // What is the type of x }
To handle this tricky situation, Kotlin provides an is keyword to verify the variable type. The syntax for this is as follows:
x is Intx is Char
This check will return true if x is an integer or character; otherwise, it will return false. Check the following examples:
fun func(x: Any) { if(x is Float){ println("x is Float") } else if(x is String){ println("x is String")}
!is can be used to verify whether or not a variable is a required type:
fun func(x: Any) { if(x !is Float){ println("f is not Float") }}
In this section, we will learn about one of the most important topic of Kotlin, which is null safety. We will learn how null safety works, why it is important, and how Kotlin helps to improve the code quality. Later in this section, we will learn about type casting and its implications and we will conclude this chapter by discussing to useful data structures Pair and Triple.
