SlideShare a Scribd company logo
Kotlin Indepth A Guide To A Multipurpose
Programming Language For Serverside Frontend
Android And Multiplatform Mobile Aleksei Sedunov
download
https://ebookbell.com/product/kotlin-indepth-a-guide-to-a-
multipurpose-programming-language-for-serverside-frontend-
android-and-multiplatform-mobile-aleksei-sedunov-43887986
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Kotlin Indepth Volii A Comprehensive Guide To Modern Multiparadigm
Language Aleksei Sedunov
https://ebookbell.com/product/kotlin-indepth-volii-a-comprehensive-
guide-to-modern-multiparadigm-language-aleksei-sedunov-44848948
Kotlin Indepth Voli A Comprehensive Guide To Modern Multiparadigm
Language Aleksei Sedunov
https://ebookbell.com/product/kotlin-indepth-voli-a-comprehensive-
guide-to-modern-multiparadigm-language-aleksei-sedunov-44848972
Kotlin Indepth Vol I A Comprehensive Guide To Modern Multiparadigm
Language Aleksei Sedunov
https://ebookbell.com/product/kotlin-indepth-vol-i-a-comprehensive-
guide-to-modern-multiparadigm-language-aleksei-sedunov-44859406
Pro Spring Boot 3 With Kotlin Indepth Guide To Best Practices For
Cloudnative And Microservices Development 3rd Edition Peter Spth
https://ebookbell.com/product/pro-spring-boot-3-with-kotlin-indepth-
guide-to-best-practices-for-cloudnative-and-microservices-
development-3rd-edition-peter-spth-231835744
Pro Spring Boot 3 With Kotlin Indepth Guide To Best Practices For
Cloudnative And Microservices Development 3rd Edition Peter Spth
https://ebookbell.com/product/pro-spring-boot-3-with-kotlin-indepth-
guide-to-best-practices-for-cloudnative-and-microservices-
development-3rd-edition-peter-spth-231835754
Pro Spring 6 With Kotlin An Indepth Guide To Using Kotlin Apis In
Spring Framework 6 1st Edition Peter Spth
https://ebookbell.com/product/pro-spring-6-with-kotlin-an-indepth-
guide-to-using-kotlin-apis-in-spring-framework-6-1st-edition-peter-
spth-52328224
Programming Kotlin Familiarize Yourself With All Of Kotlins Features
With This Indepth Guide Stephen Samuel
https://ebookbell.com/product/programming-kotlin-familiarize-yourself-
with-all-of-kotlins-features-with-this-indepth-guide-stephen-
samuel-22009530
Kotlin In Action Second Edition Meap V09 Chapters 1 To 10 Of 16
Svetlana Isakova
https://ebookbell.com/product/kotlin-in-action-second-edition-
meap-v09-chapters-1-to-10-of-16-svetlana-isakova-50703078
Kotlin In Action Dmitry Jemerov Svetlana Isakova
https://ebookbell.com/product/kotlin-in-action-dmitry-jemerov-
svetlana-isakova-7032742
Kotlin Indepth A Guide To A Multipurpose Programming Language For Serverside Frontend Android And Multiplatform Mobile Aleksei Sedunov
Kotlin Indepth A Guide To A Multipurpose Programming Language For Serverside Frontend Android And Multiplatform Mobile Aleksei Sedunov
Kotlin Indepth A Guide To A Multipurpose Programming Language For Serverside Frontend Android And Multiplatform Mobile Aleksei Sedunov
Kotlin In-Depth
A Guide to a Multipurpose Programming
Language for Server-Side, Front-End,
Android, and
Multiplatform Mobile
Aleksei Sedunov
www.bpbonline.com
FIRST EDITION 2022
Copyright © BPB Publications, India
ISBN: 978-93-91030-63-6
All Rights Reserved. No part of this publication may be reproduced, distributed or transmitted in any
form or by any means or stored in a database or retrieval system, without the prior written permission
of the publisher with the exception to the program listings which may be entered, stored and executed
in a computer system, but they can not be reproduced by the means of publication, photocopy,
recording, or by any electronic and mechanical means.
LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY
The information contained in this book is true to correct and the best of author’s and publisher’s
knowledge. The author has made every effort to ensure the accuracy of these publications, but
publisher cannot be held responsible for any loss or damage arising from any information in this
book.
All trademarks referred to in the book are acknowledged as properties of their respective owners but
BPB Publications cannot guarantee the accuracy of this information.
www.bpbonline.com
Dedicated to
Tatiana,
my guiding light
and the incessant source of inspiration
About the Author
Aleksei Sedunov has been working as a Java developer since 2008. After
joining JetBrains in 2012, he’s been actively participating in the Kotlin
language development focusing on IDE tooling for the IntelliJ platform.
Currently, he’s working in a DataGrip team, a JetBrains Database IDE,
carrying on with using Kotlin as the main development tool.
About the Reviewers
Sanjay Kakadiya is currently working as a Sr Software developer of the e-
commerce Android app. He completed his Bachelor of Engineering in IT
from Gujarat University in 2012 and has more than 9 years of experience in
mobile application development using Java, React Native, and Kotlin. He
has been a co-organizer of the Ahmedabad Web and Mobile Developers
Meetup group since 2015. He is a Kotlin and Java addict. He is obsessed
with the elegant and functional style code. He mainly focuses on the mobile
apps architecture.
Sanjay has created and improvised dozens of successful applications for
clients in areas of social networking, education, video streaming,
entertainment, self-help, fitness, lifestyle, and commerce.
Touhidul Islam is currently working as a mobile engineer at Toptal. He has
a good grasp at data structure and algorithms and an eye for better
architecture. Although, he has professional software experience in both
cross-platform mobile and back-end technologies, he shines on native
Android development. He has hands-on experience working at startups
from his early career and one of the software developed by him earns about
40% of the revenue for that company. He later joined a big tech company
developing pixel-perfect customer-facing mobile software and led the
development there. He is currently working with Australia’s one of the
leading service provider companies to revolutionize how people interact
with service providers.
Acknowledgements
Above all others, I would like to give my gratitude to the entire Kotlin team
at JetBrains which has created such a beautiful language and continues to
relentlessly work on its improvement – especially Andrey Breslav who’s
been leading the language design from the very first day.
I’m really grateful to everyone at BPB Publications for giving me this
splendid opportunity for writing this book and lending a tremendous
support in improving the text before it gets to the readers. Many thanks to
Sanjay Kakadiya and Touhidul Islam for their great help as technical
reviewers for the second edition.
Last but not least, I’d like to thank my beloved family for their support
throughout the work on the book.
Preface
Since its first release in 2016 (and even long before that), Kotlin has been
gaining popularity as a powerful and flexible tool in a multitude of
development tasks being equally well-equipped for dealing with mobile,
desktop, and server-side applications and finally, getting its official
acknowledgment from Google in 2017 and 2018 as a primary language for
Android development. This popularity is well-justified since language
pragmatism, the tendency to choose the best practice among known
solutions was one of the guiding principles of its design.
With the book you’re holding in your hands, I’d like to invite you to the
beautiful world of Kotlin programming where you can see its benefits for
yourself. After completing this book, you’ll have all the necessary
knowledge to write in Kotlin on your own.
The first volume deals with the fundamentals of Kotlin language such as its
basic syntax, procedural, object-oriented, and functional programming
aspects as well as the Kotlin Standard Library. The book is divided into 9
chapters as follows:
Chapter 1 explains key ideas behind the language design, gives an
overview of the Kotlin ecosystem and tooling, and guides the reader
through the first steps required to set up a Kotlin project in various
environments.
Chapter 2 introduces the reader to the Kotlin syntax, explains how to use
variables, and describes simple data types such as integers or Boolean
values as well as their built-in operations. It also addresses the basics of
more complex data structures such as strings and arrays.
Chapter 3 discusses the syntax of Kotlin functions and explains the uses of
various control structures supported by Kotlin such as binary/multiple
choice, iteration, and error handling. Additionally, it addresses the matter of
using packages for code structuring.
Chapter 4 introduces the reader to the basic aspects of object-oriented
programming in Kotlin. It explains how to create and initialize a class
instance and how to control member access, describe the use of object
declarations and non-trivial kinds of properties, and brings up the concept
of type nullability.
Chapter 5 explains the functional aspects of Kotlin and introduces the
reader to the idea of higher-order and anonymous functions, addresses the
uses of inline functions, and explains how one can add features to existing
types using extension functions and properties.
Chapter 6 explains the use of special kinds of classes tailored at specific
programming tasks: data classes for simple data holders, enumerations for
representing a fixed set of instances, and inline classes for creating
lightweight wrappers.
Chapter 7 explores object-oriented features introduced in Chapters 4 and 6
focusing on the idea of a class hierarchy. It explains how to define
subclasses, how to use abstract classes and interfaces, and how to restrict
hierarchies using sealed classes.
Chapter 8 describes a major part of the Kotlin standard library which is
concerned with various collection types and their operations as well as
utilities simplifying file access and stream-based I/O.
Chapter 9 introduces the idea of generic declarations and explains how to
define and use generic classes, functions, and properties in Kotlin. It also
explains the notion of variance and how it can be used to improve flexibility
of your generic code.
The second volume introduces you to the more advanced Kotlin features
such as reflection, domain-specific languages and coroutines, discusses
Java/Kotlin interoperability issues, and explains how Kotlin can be used in
various development areas, including testing, Android applications, and
Web. It’s divided into the following 8 chapters:
Chapter 10 addresses the use of annotations which allow you to
accompany the Kotlin code with various metadata and explains the basics
of Reflection API which provides access to runtime representation of Kotlin
declarations.
Chapter 11 describes some advanced features which help developer in
composing flexible APIs in the form of the domain-specific languages:
operator overloading, delegated properties, and builder-style DSLs based on
the higher-order functions.
Chapter 12 discusses common issues of combining Java and Kotlin code
within the same codebase and explains the specifics of using Java
declarations in Kotlin code and vice versa.
Chapter 13 introduces the reader to the Kotlin coroutines library which
introduces a set of building blocks for programming asynchronous
computations. Additionally, it describes some utilities simplifying the use of
Java concurrency API in Kotlin code.
Chapter 14 discusses the KotlinTest, a popular testing framework aimed
specifically at the Kotlin developers. It describes various specification
styles, explains the use of assertion API, and addresses more advanced
issues like using fixtures and test configurations.
Chapter 15 serves as an introduction to using Kotlin for development on
the Android platform. It guides the reader through setting up an Android
Studio project and explains basic aspects of Android development using an
example of a simple calculator application.
Chapter 16 explains the basic features of the Ktor framework aimed at
development of connected applications which make heavy use of Kotlin
features and asynchronous computations.
Chapter 17 describes how to build a microservice application using Spring
Boot and Ktor frameworks.
Code Bundle and Coloured Images
Please follow the link to download the
Code Bundle and the Coloured Images of the book:
https://rebrand.ly/04dc29
The code bundle for the book is also hosted on GitHub at
https://github.com/bpbpublications/Kotlin-In-Depth. In case there's an
update to the code, it will be updated on the existing GitHub repository.
We have code bundles from our rich catalogue of books and videos
available at https://github.com/bpbpublications. Check them out!
Errata
We take immense pride in our work at BPB Publications and follow best
practices to ensure the accuracy of our content to provide with an indulging
reading experience to our subscribers. Our readers are our mirrors, and we
use their inputs to reflect and improve upon human errors, if any, that may
have occurred during the publishing processes involved. To let us maintain
the quality and help us reach out to any readers who might be having
difficulties due to any unforeseen errors, please write to us at :
errata@bpbonline.com
Your support, suggestions and feedbacks are highly appreciated by the BPB
Publications’ Family.
Did you know that BPB offers eBook versions of every book
published, with PDF and ePub files available? You can upgrade to
the eBook version at www.bpbonline.com and as a print book
customer, you are entitled to a discount on the eBook copy. Get in
touch with us at: business@bpbonline.com for more details.
At www.bpbonline.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 BPB books and eBooks.
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
business@bpbonline.com 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
www.bpbonline.com. We have worked with thousands of developers
and tech professionals, just like you, to help them share their insights
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.
Reviews
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 BPB can understand what you think about our
products, and our authors can see your feedback on their book.
Thank you!
For more information about BPB, please visit www.bpbonline.com.
Table of Contents
1. Kotlin - Powerful and Pragmatic
Structure
Objectives
What is Kotlin?
Safe
Multiparadigm
Concise and expressive
Interoperable
Multiplatform
Kotlin ecosystem
Coroutines
Testing frameworks
Android development
Web development
Desktop applications
Getting started with Kotlin
Setting up an IntelliJ project
Using REPL
Interactive editors
Setting up an Eclipse project
Conclusion
Points to remember
Questions
2. Language Fundamentals
Structure
Objectives
Basic syntax
Comments
Defining a variable
Identifiers
Mutable variables
Expressions and operators
Primitive types
Integer types
Floating-point types
Arithmetic operations
Bitwise operations
Char type
Numeric conversions
Boolean type and logical operations
Comparison and equality
Strings
String templates
Basic string operations
Arrays
Constructing an array
Using arrays
Conclusion
Points to remember
Multiple choice questions
Answers
Questions
3. Defining Functions
Structure
Objective
Functions
Function anatomy
Trailing commas
Positional vs named arguments
Overloading and default values
Varargs
Function scope and visibility
Packages and imports
Packages and directory structure
Using import directives
Conditionals
Making decisions with if statements
Ranges, progressions, and in operation
when statements and multiple choice
Loops
while/do-while loop
Iterables and for loop
Changing loop control-flow: break and continue
Nested loops and labels
Tail-recursive functions
Exception handling
Throwing an exception
Handling errors with try statements
Conclusion
Points to remember
Multiple choice questions
Answers
Questions
Key terms
4. Working with Classes and Objects
Structure
Objectives
Defining a class
A class anatomy
Constructors
Member visibility
Nested classes
Local classes
Nullability
Nullable types
Nullability and smart casts
Not-null assertion operator
Safe call operator
Elvis operator
Properties: Beyond simple variables
Top-level properties
Late initialization
Using custom accessors
Lazy properties and delegates
Objects and companions
Object declarations
Companion objects
Object expressions
Conclusion
Points to remember
Multiple choice questions
Answers
Questions
Key terms
5. Leveraging Advanced Functions and Functional Programming
Structure
Objective
Functional programming in Kotlin
Higher-order functions
Functional types
Lambdas and anonymous functions
Callable references
Inline functions and properties
Non-local control flow
Extensions
Extension functions
Extension properties
Companion extensions
Lambdas and functional types with the receiver
Callable references with receiver
Scope functions
run / with
run without context
let
apply / also
Extensions as class members
Conclusion
Points to remember
Questions
Key terms
6. Using Special-Case Classes
Structure
Objective
Enum classes
Exhaustive when expressions
Declaring enums with custom members
Using common members of enum classes
Data classes
Data classes and their operations
Destructuring declarations
Inline classes
Defining an inline class
Unsigned integers
Conclusion
Points to remember
Questions
Key terms
7. Exploring Collections and I/O
Structure
Objective
Collections
Collection types
Iterables
Collections, lists, and sets
Sequences
Maps
Comparables and comparators
Creating a collection
Basic operations
Accessing collection elements
Collective conditions
Aggregation
Filtering
Transformation
Extracting subcollections
Ordering
Files and I/O streams
Stream utilities
Creating streams
URL utilities
Accessing file content
File system utilities
Conclusion
Points to remember
Multiple choice questions
Answers
Questions
8. Understanding Class Hierarchies
Structure
Objective
Inheritance
Declaring a subclass
Subclass initialization
Type Checking and Casts
Common methods
Abstract classes and interfaces
Abstract classes and members
Interfaces
Sealed classes
Delegation
Conclusion
Points to remember
Multiple choice questions
Answers
Questions
9. Generics
Structure
Objective
Type parameters
Generic declarations
Bounds and constraints
Type erasure and reification
Variance
Variance: Distinguishing producers and consumers
Variance at the declaration site
Use-site variance with projections
Star projections
Type aliases
Conclusion
Points to remember
Questions
10. Annotations and Reflection
Structure
Objectives
Annotations
Defining and using annotation classes
Built-in annotations
Reflection
Reflection API overview
Classifiers and types
Callables
Conclusion
Questions
11. Domain-Specific Languages
Structure
Objective
Operator overloading
Unary operations
Increments and decrements
Binary operations
Infix operations
Assignments
Invocations and indexing
Destructuring
Iteration
Delegated properties
Standard delegates
Creating custom delegates
Delegate representation
Higher-order functions and DSLs
Fluent DSL with infix functions
Using type-safe builders
@DslMarker
Conclusion
Questions
12. Java Interoperability
Structure
Objective
Using Java code from Kotlin
Java methods and fields
Unit vs void
Operator conventions
Synthetic properties
Platform types
Nullability annotations
Java/Kotlin type mapping
Single abstract method interfaces
Working with Java records
Using the Java-to-Kotlin converter
Using the Kotlin code from Java
Accessing properties
File facades and top-level declarations
Objects and static members
Changing the exposed declaration name
Generating overloads
Declaring exceptions
Inline functions
Type aliases
Exposing Kotlin classes as Java records
Conclusion
Questions
13. Concurrency
Structure
Objective
Coroutines
Coroutines and suspending functions
Coroutine builders
Coroutine scopes and structured concurrency
Coroutine context
Coroutine control-flow
Job lifecycle
Cancellation
Timeouts
Coroutine dispatching
Exception handling
Concurrent communication
Channels
Producers
Tickers
Flows
Actors
Using Java concurrency
Starting a thread
Synchronization and locks
Coroutine debugger
Conclusion
Questions
14. Testing with Kotlin
Structure
Objective
KotlinTest specifications
Getting started with KotlinTest
Specification styles
Assertions
Matchers
Inspectors
Handling exceptions
Testing non-deterministic code
Property-based testing
Fixtures and configurations
Providing a fixture
Test configuration
Conclusion
Questions
15. Android Applications
Structure
Objective
Getting started with Android
Setting up an Android Studio project
Gradle build scripts
Activity
Using an emulator
Activities
Designing an application UI
Implementing an activity class
View binding
Preserving the activity state
Conclusion
Questions
16. Web Development with Ktor
Structure
Objective
Introducing Ktor
Server features
Routing DSL
Handling calls
HTML DSL
Sessions support
Client features
Requests and responses
Cookies
Conclusion
Questions
17. Building Microservices
Structure
Objectives
The microservice architecture
Introducing Spring Boot
Setting up a project
Deciding on the Services API
Implementing a random generator service
Implementing a password generator service
Microservices with Ktor
Using the JSON serialization feature
Implementing a password generator service
Conclusion
Questions
Index
CHAPTER 1
Kotlin - Powerful and Pragmatic
This chapter is meant to explain the major features which make Kotlin an
excellent and efficient language for modern application development and
the reasons why you might want to learn it. We’ll learn the basic ideas
which stand behind the Kotlin design and get an overview of Kotlin
libraries and frameworks for different application areas such as Android
applications, concurrency, testing and web development. In conclusion,
we’ll guide you through the steps required to set up a Kotlin project in two
popular development environments, IntelliJ IDEA and Eclipse, and
introduce you to the interactive Kotlin shell.
Structure
We will cover the following topics:
What is Kotlin?
Major components of the Kotlin ecosystem
Setting up a Kotlin project in IDE and online editors
Objectives
At the end of the chapter, you’ll get an understanding of the basic Kotlin
principles and the Kotlin ecosystem as well as what simple a Kotlin
program looks like and you will be able to set up a project in common
IDEs.
What is Kotlin?
Kotlin is a multiplatform and multiparadigm programming language
emphasizing safety, conciseness, and interoperability. Conceived in late
2010, it had reached its first release in February 2016 and has been steadily
becoming an increasingly popular and promising tool in many development
areas such as Android development, desktop applications, or server-side
solutions. The company which stands behind the language and has been
investing in its development ever since is JetBrains which is famous for its
excellent software engineering tools such as IntelliJ IDEA. By August
2020, Kotlin had reached version 1.4, acquiring massive community, well-
developed ecosystems, and extensive tooling. Having overgrown an original
intent of creating a better Java alternative, it now embraces multiple
platforms, including Java Virtual Machine, Android, JavaScript, and native
applications. In 2017, Google announced Kotlin an officially supported
language of the Android platform which gave a tremendous boost to the
language popularity. Nowadays, a lot of companies – among them Google,
Amazon, Netflix, Pinterest, Uber, and many others – are using Koltin for
production development, and the number of open positions for Kotlin
developers is growing steadfast.
It all became possible thanks to the efforts devoted to the careful language
design and putting into action the primary traits which make Kotlin such an
excellent development tool. The language philosophy has mainly arisen
based on the problems it was intended to solve back in 2010. By that time,
JetBrains had already accumulated an extensive Java code base for products
centered around its IntelliJ platform which was arguably the most known
IntelliJ IDEA, had also included a set of minor IDEs dedicated to different
technologies such as WebStorm, PhpStorm, RubyMine, etc. The
maintenance and growth of such codebase, however, was being hampered
by Java itself due to its slow evolution and lack of many useful features
which at that moment had already been available in such languages as Scala
and C#. Having researched the JVM languages available at that moment,
the company concluded that no existing language proved satisfiable for
their needs and decided to invest resources into implementation of their
own language. The new language was eventually named Kotlin as a tribute
to an island near Saint-Peteresburg, Russia where most of its development
team was located.
So what are those traits which have been shaping the language from the
very beginning? In fact, we’ve already given the answer in its definition.
The reason behind Kotlin is a need for a multiparadigm language
emphasizing safety, conciseness, and interoperability. Let’s look at these
traits in more detail.
Safe
For a programming language, being safe means being able to prevent a
programmer’s errors. In practice, designing the language with respect to
safety is a matter of tradeoff since error prevention typically comes at a
cost. You give the compiler more detailed information about your program
or allow it to spend more time reasoning about it correctness (probably
both). One of Kotlin design goals was to find a sort of golden mean;
contriving a language with more stronger safety guarantees than Java, but
not so strong to frustrate a developer’s productivity. And although the
Kotlin solution is by no means absolute, it has repeatedly proved to be an
efficient choice in practice.
We’ll discuss various aspects of Kotlin safety as we go through the book.
Here, we’d like to point out some major features:
Type inference which allows the developer to omit explicit declaration
types in most cases (Java 10 introduced this for local variables)
Nullable types regulate the usage of null and help to prevent infamous
NullPointerException
Smart casts which simplify type casting reducing the chance of casting
errors at runtime
Multiparadigm
Initially, the meaning behind Kotlin multiparadigmality implied the support
of functional programming in addition to the conventional object-oriented
paradigm typical for many mainstream programming languages such as
Java. The functional programming is based around the idea of using
functions as values: passing them as parameters or returning from other
functions, declaring locally, storing in variables, etc. Another aspect of the
functional paradigm is an idea of immutability which means that objects
you manipulate can’t change their state once created and functions can’t
produce side effects.
The major benefit of this approach is improved programming flexibility.
Being able to create a new kind of abstraction, you can write more
expressive and concise code, thus increasing your productivity. Note that
although functional programming principles can be employed in many
languages (Java’s anonymous classes, for example, were an obvious choice
before introduction of lambdas), not every language has necessary syntactic
facilities encouraging the writing of such code. Kotlin, on the contrary,
included necessary features right from the start. They include, in particular,
functional types smoothly integrating functions into the language type
systems and lambda expressions meant to create functionally-typed values
from code blocks. The standard library as well as external frameworks
provides an extensive API facilitating the functional style. Nowadays, many
of that also apply to Java which had introduced functional programming
support starting with Java 8. But its expressiveness still somewhat falls
behind Kotlin’s.
We’ll cover the basics of functional programming in Chapter 5, Leveraging
Advanced Functions and Functional Programming, but its applications and
examples will accompany us throughout the book.
Over its growth, the language also began to exhibit two more programming
paradigms. Thanks to the ability to design APIs in the form of domain-
specific languages (DSLs) Kotlin can be used in a declarative style. In fact,
many Kotlin frameworks provide their own DSLs for specific tasks with no
need to sacrifice type-safety or expressive power of the general-purpose
programming language. For example, the exposed framework includes a
DSL for defining database schema and manipulating its data, whereas
kotlinx.html gives a concise and type-safe alternative to HTML template
languages. In Chapter 11, Domain-Specific Languages, we’ll discuss these
examples in more detail as well as learn how to create our own DSLs.
One more paradigm, namely, concurrent programming, entered the
language with the introduction of coroutines. Although, concurrency
support by itself is present in many languages, including Java, the Kotlin
features a rich set of programming patterns which enable a new
programming approach. We’ll cover the basics of this approach in Chapter
13, Concurrency.
All in all, the presence of multiple paradigms greatly increases the
language’s expressive power, making it a more flexible and multi-purposed
tool.
Concise and expressive
Developer productivity is largely tied with the ability to quickly read and
understand the code, be it some other developer’s work or maybe your own
after a significant time has passed. In order to understand what a specific
piece of code does, you need to also understand how it’s related to other
parts of your program. That’s why reading the existing code generally takes
more time than writing a new one and that’s why language conciseness and
the ability to clearly express a programmer’s intents without much
information noise is a crucial aspect of language efficiency as a
development tool.
The designers of Kotlin did their best to make language as concise as
possible, eliminating a lot of notorious Java boilerplate such as field getters
and setters, anonymous classes, explicit delegation, and so on. On the other
hand, they made sure the conciseness is not overtly abused – unlike Scala;
for example, Kotlin doesn’t allow the programmer to define custom
operators, but only redefine existing ones since the former tends to
obfuscate the operation meaning. In the course of the book, we’ll see
numerous implications of this decision and how useful it turned to be.
Another aspect of Kotlin’s conciseness is tightly related to the DSLs (see
Chapter 11, Domain-Specific Languages which greatly simplify the
description of specific programming domains with a minimum of syntactic
noise.
Interoperable
Java interoperability was a major point in Kotlin design since the Kotlin
code wasn’t mean to exist in isolation, but to cooperate as smoothly as
possible with the existing codebase. That’s why Kotlin designers made sure
that not only the existing Java code can be used from Kotlin, but that Kotlin
code can also be used from Java with little to no effort. The language also
includes a set features specifically meant to tune interoperability between
Java and Kotlin.
As the language overgrew, the JVM and spread to other platforms,
interoperability guarantees were extended as well to cover interaction with
JavaScript code for the JS platform and C/C++/Objective C/Swift code for
native applications.
We’ll devote Chapter 12, Java Interoperability, to discuss the Java
interoperability issues and how Kotlin and Java can be mixed together in
the same project.
Multiplatform
Multiplatformity wasn’t an original intent of Kotlin designers, but rather
manifested itself as a result of language evolution and adaptation to the
needs of the development community. While JVM and Android remain a
primary target of Kotlin development, nowadays the supported platforms
also cover the following:
JavaScript, including browser and Node.js applications as well as
JavaScript libraries
Native applications and libraries for macOS, Linux and Windows
Since 1.3 Kotlin supports multiplatform development with major uses cases
being sharing the code between Android and iOS applications and creating
multiplatform libraries for JVM/JS/Native world.
Kotlin ecosystem
Throughout its evolution, Kotlin has given rise to a rich set of libraries and
frameworks covering most of software development aspects. Here, we will
try to give you an overview of available tools which hopefully will serve as
a guide in this ocean of possibilities. Note, however, that as the ecosystem
is continuously growing, the state-of-the-art presented in this book at the
moment that is being written will inevitably fall out of date, so don’t
hesitate looking for it by yourself. A good starting point is a community-
updated list of libraries and frameworks available on the Awesome Kotlin
website at https://interlink.
It’s also worth noting that thanks to well-conceived Java interoperability
Kotlin applications may benefit from a whole lot of existing Java libraries.
In some cases, they have specific Kotlin extensions allowing one to write
more idiomatic code.
Coroutines
Thanks to the concept of suspendable computations, Kotlin is able to
support concurrency-related programming patterns such as aync/await,
futures, promises, and actors. The Coroutines framework provide a
powerful, elegant, and easily scalable solution to concurrency problems in
the Kotlin application whether it is a server-side, mobile, or desktop one.
The major features of the coroutines include, among others:
A lightweight alternative to threads
Flexible thread dispatching mechanism
Suspendable sequences an iterators
Sharing memory via channels
Using actors to share mutable state via message sending
We’ll cover the basics of the coroutine API in Chapter 13, Concurrency,
which deals with concurrency issues in Kotlin.
Testing frameworks
Apart from familiar Java testing frameworks such as JUnit, TestNG, and
Mockito which can be with little effort employed in a Kotlin application,
the developers can enjoy the power of Kotlin-tailored frameworks
providing useful DSLs for testing purposes; be it test definitions or mocking
your objects. In particular, we’d like to point out the following:
Mockito-Kotlin, an extension for the popular Mockito framework
simplifying object mocking in Kotlin.
Spek, a behavior-driven testing framework supporting Jasmine- and
Gherkin-styled definition of test cases.
KotlinTest, a ScalaTest-inspired framework which supports flexible
test definitions and assertions.
In Chapter 14, Testing with Kotlin, we’ll pay more attention to the features
provided by Spek and Mockito and consider how to use them in your
projects.
Android development
Android is one of the major and most actively growing application areas of
Kotlin. This has become especially relevant after Google’s announced the
Kotlin a first-class Android language implying, in particular, that Android
tooling is now being designed and developed with due regard to the Kotlin
features as well. Apart from the excellent programming experience brought
by the Android Studio plugin, Android developers can benefit from the
smooth interoperability with many popular frameworks such as Dagger,
ButterKnife, and DBFlow. Among Kotlin-specific Android tools, we’d like
to pay attention to Anko and Kotlin Android Extensions:
Kotlin Android Extensions is a compiler plugin whose main feature is
data-binding which allows you to use XML-defined views as if they’re
implicitly defined in your code, thus avoiding the infamous
findViewById() calls. It supports view caching and the ability to
automatically generate Parcelable implementations for user-defined
classes. Thanks to this there is no need to employ external frameworks
like ButterKnife in pure Kotlin projects.
Anko is a Kotlin library which simplifies the development of Android
applications. In addition to numerous helpers, it includes a domain-
specific language (Anko Layouts) for composing dynamical layouts
accompanied by the UI preview plugin for Android Studio as well
database query DSL based around Android SQLite.
We’ll cover some of these features in Chapter 15, Android Applications,
which introduces the reader to Kotlin-powered Android development.
Web development
Web/Enterprise application developers can also benefit from using Kotlin.
Popular frameworks such as Spring 5.0 and Vert.x 3.0 include Kotlin-
specific extensions which allow you to use their functionality in more
Kotlin-idiomatic way. You can employ pure Kotlin solutions using a variety
of frameworks:
Ktor a JetBrains framework for creating an asynchronous server and
client applications.
kotlinx.html a domain-specific language for building HTML
documents.
Kodein a dependency injection framework.
We’ll discuss specifics of building web applications and microservices
using Ktor and Spring in Chapter 16, Web Development with Ktor and
Chapter 17, Building Microservices, respectively.
Desktop applications
Developers of desktop applications for the JVM platform can employ
TornadoFX, a JavaFX-based framework. It provides helpful domain-
specific languages for building GUI and style description via CSS, support
FXML markup, and MVC/MVP architecture. It also comes with an IntelliJ
plugin simplifying the generation of TornadoFX projects, views, and other
components.
Getting started with Kotlin
Now, you should have an idea of the Kotlin ecosystem, and the only thing
we need to discuss before we can start exploring the language is how to set
up a working environment.
Setting up an IntelliJ project
Although Kotlin by itself, like most programming languages, is not tied to a
particular IDE or text editor, the choice of development tools has a great
impact on the developer’s productivity. As of now, the JetBrains IntelliJ
platform provides the most powerful and comprehensive support of the
Kotlin development lifecycle. Right from the start, Kotlin IDE has been
developed in tight integration with the language itself which helps it to stay
up-to-date with Kotlin changes. For these reasons, we recommend using it
for your own projects and employ it for the examples in the book.
Since IntelliJ IDEA 15 Kotlin support is bundled into the IDE distribution,
you won’t need to install any external plugins to facilitate Kotlin
development. For this book, we’ve been using IntelliJ IDEA 2020.3
released in the late December, 2020.
If you don’t have an IDEA installed, you can download the latest version
from www.jetbrains.com/idea/download and follow the installation
instructions from https://www.jetbrains.com/help/idea/install-and-set-
up-product.html. IDEA comes in two editions: Community which is free
and open-source and Ultimate which is a commercial product. The major
difference is that the Ultimate edition includes a set of features related to
the development of web and enterprise applications as well as database
tools. You can find a more detailed list of changes at the download page.
For this book, we won’t need the Ultimate features, so IDEA Community is
more than enough.
If you haven’t opened a project in IntelliJ before, you’ll see a welcome
screen on startup where you can click on the Create New Project option to
go directly to the project wizard dialog box. Otherwise, IntelliJ opens the
recently edited project(s); in this case, choose File | New | Project in the
application menu.
Project types are grouped into categories you can see in the left pane. The
exact set of categories and projects depends on the plugin installed, but for
now, we’re interested in the Kotlin category which is available out-of-the
box thanks to the bundled Kotlin plugin. When you click on it, you’ll see
the list of available project templates (Figure 1.1):
Figure 1.1: New project wizard (step 1)
As of version 1.4.21 (which we’ve used when writing this book), the Kotlin
plugin supports creating of projects targeting JVM, JavaScript, native
applications as well several cases of multiplatform projects such as mobile
applications targeting both Android and iOS. The platform determines both
the type of compiler artifacts (bytecode for the JVM, .js files for JavaScript,
and platform-specific executables for Kotlin/Native) and a set of available
dependencies your project can use; a project targeting JavaScript, for
example, can’t access classes from the Java class library. As we go ahead,
our primary interest will be the JVM applications, so for this example, we’ll
choose the corresponding option in the JVM group.
The wizard also allows you to choose a particular build system for
automating common tasks related to the project lifecycle: compilation,
testing, packaging, publication, and so on. Detailed treatment of a particular
build system specifics goes beyond the scope of the book and has little
effect on our code examples apart from the project file structure. So in this
tutorial, we’ll just choose IntelliJ as the default option before proceeding
with project creation.
Besides that, you’ll need to provide the project name and location which is
a root directory for the project-related content, including its source files.
Note that IntelliJ suggests the location automatically based on the project
name you’ve typed, but you can change it if necessary.
Since our project targets the JVM platform, we also have to specify a
default JDK to use for the project compilation. That would allow our
project to use classes from the Java standard library as well as compile Java
sources in mixed-language projects. In Chapter 12, Java Interoperability,
we’ll cover such projects in more detail and also discuss how to introduce
Kotlin support to the existing Java projects.
We recommend using JDK 8 or higher. For this example, we’ve chosen the
latest (as of the book’s writing) release version of Oracle OpenJDK 15.
Usually, IntelliJ auto-detects the JDK installed on your machine, but if that
doesn’t happen or none of preconfigured JDKs in the Project SDK list suit
your purposes, you can add a new one by choosing Add JDK options
specifying the path to some preinstalled JDK instance, or Download JDK to
have IDE download one of the popular JDK implementations (such as
OpenJDK or Corretto) for you.
One more thing worth mentioning is a Kotlin runtime library the IntelliJ has
preconfigured for our project. By default, the project will reference a library
in the IDE plugin directory which means it’s upgraded automatically
whenever you update the plugin itself. If you, however, want your project to
depend on a particular version of Kotlin runtime, only updating it manually
out of necessity, you may change that behavior. To do that, expand the
Kotlin Runtime group, click on the Create button and choose the Copy to
option specifying the directory name where the library needs to be kept.
Clicking on the Next button will bring the second step of the project wizard
where you can specify additional options such as minimum JVM version on
which your application is supposed to run, a test framework, and a
predefined template the IDE will use to generate the initial project structure
(for example; a console or Ktor-based web application). The example of
step 2 is shown in Figure 1.2:
Figure 1.2: New project wizard (step 2)
In the final step, click on the Finish button and you will get IntelliJ to
generate and open an empty project. By default, IntelliJ presents it in a two-
panel view: Project tool window on the left and the editor area occupying
most of the remaining area. The editor is initially empty since we haven’t
opened a single file yet, so we’ll first focus on the Project window and use
it to create a new Kotlin file.
If the Project tool window is absent, you can bring it by clicking on the
Project button (usually, it’s on the left-hand side of the window border) or
using the shortcut Alt+1 (Meta+1).
The Project window shows the hierarchical structure of your project. Let’s
expand the root nodes and see what it contains (Figure 1.3). Currently,
we’re mostly interested in the following three items:
src directory which serves as a content root containing project
source files.
out directory where the compiler puts the generated bytecode (absent
initially but created automatically on project compilation).
External Libraries which list all libraries the project depends on.
Figure 1.3: Project structure tool window
Now, right-click on the src/main/kotlin directory and select the New |
Kotlin File/Class command. In the dialog box that follows, type a file
name main.kt. Make sure that the Kind field is set to File and click on OK.
You’ll see the Project window updated to show a new file which is at the
same time opened in the editor. Note that Kotlin source files must have the
.kt extension.
At last, we’re ready to write an actual code. Let’s type the following in the
editor window (Figure 1.3):
fun main() {
println(“Hello, KotlinVerse!”)
}
The preceding code defines the main function which serves as an entry-
point for the Kotlin application. The function body consists of a single
statement, a call to the standard library function println() writing its
argument to the program’s standard output with a new line added at the end.
Figure 1.4: “Hello, World“ program
Java developers will surely recognize a similarity between this code and the
following Java program:
public class Main {
public static void main(String[] args) {
System.out.println(“Hello, World!”)
}
}
In fact, JVM’s version of the Kotlin println() function is just a call to
System.out.println(). Since the JVM entry-point must be a static class
method, you might be wondering how the Kotlin application is started
without defining a single class. The answer is that although we haven’t
defined a class explicitly, the Kotlin compiler will create one behind the
scenes, putting there the JVM’s entry-point which in turn would call our
main() function. We’ll get back to these so called facade classes in Chapter
12, Java Interoperability because they constitute a major aspect of
Kotlin/Java interoperability.
Also, note that unlike the JVM entry-point which is supposed to take an
array of command-line arguments as its parameter, our main() function has
no parameters at all. This comes in handy for the cases when command-line
arguments are not used. If necessary, however, you can still define the
entry-point taking these arguments:
fun main(args: Array<String>) {
println(args)
}
Parameterless main() is in fact a comparatively recent feature introduced in
Kotlin 1.3. In earlier language versions, the only acceptable entry point was
the one taking the String<Array> argument just like its Java counterpart.
This feature took further development in Kotlin 1.4 where the compiler
produces a warning if the main() parameter is not really used in the
function’s body (see Figure 1.5):
Figure 1.5: Unused parameter in the main() function
You might’ve noticed a small green triangle on the left-hand side of the
main() definition. This line marker indicates that function main(), being an
entry-point, is executable. Clicking on that marker brings up a menu which
allows you to run or debug its code. Let’s choose the Run MainKt option
and see what happens (Figure 1.6).
MainKt, by the way, is the name of the compiler-generated facade class we
mentioned earlier. On choosing the Run command, IntelliJ compiles our
code and executes the program. The Run tool window which is opened on
program startup gets automatically linked to its standard I/O streams
serving as a built-in console. If you’ve done everything correctly, the
program will print Hello, KotlinVerse to the console and terminate
successfully.
Figure 1.6: Running a program
If you look inside the out directory, you will see the .class files generated by
the Kotlin compiler from our source program.
Congratulations! You now have an understanding of how to set up and run a
Kotlin project in the IntelliJ IDEA environment, and you are ready to delve
into the language fundamentals. KotlinVerse, here we go!
Using REPL
Kotlin plugin for IntelliJ provides an interactive shell which allows you to
evaluate program instructions on-the-fly. This can be used for quick testing
of your code or experimenting with library functions. It is also quite handy
for those who are just learning the Kotlin language. This feature is called
REPL. The meaning behind this name is “Read/Evaluate/Print Loop”
because that’s what the shell does. The reading code the user has typed,
evaluates it, prints the result (if any), and loops the whole thing over. In
order to access the REPL, select Tools | Kotlin | Kotlin REPL.
You can type the Kotlin code in the REPL window just like you do it in the
editor. The major difference is that each piece of code is compiled and
executed right after you enter it. Once the code is typed, you need to press
Ctrl + Enter (Command + Return) telling the IDE to process your input.
Let’s try it out with:
println(“Hello from REPL”)
As far as you can see, IntelliJ responds with printing “Hello from REPL” to
the console which in this case is shared with the REPL window.
The printing of the preceding string is in fact a side effect of the println()
function which by itself doesn’t return any result to the calling program. If
we, however, attempt to evaluate some expression which does have some
meaningful result, the output is slightly different. Let’s try entering 1+2*3
(Figure 1.7):
Figure 1.7: Kotlin REPL
The REPL gives us the expression result which is 7. Note the difference in
font and = icon as opposed to the println() example. This is to signify that
7 is an actual result of the code you’ve typed. To sum it up, we advise you
to get acquainted with this tool and use it throughout the book (and beyond)
to experiment with any features you feel necessary.
Interactive editors
Apart from the REPL shell available in IntelliJ, it’s worth mentioning a
similar, but more powerful online tool which lies somewhere in between a
REPL and a full-fledged IDE. The tool in question is the Kotlin
Playground. To give it a try open https://play.kotlinlang.org in your browser
(Figure 1.8).
The Kotlin Playground is basically an online environment which allows you
to explore the language with no need for an actual IDE yet having some of
its intelligent features at your disposal, including code editor, syntax and
error highlighting, code completion, and console program runner.
Figure 1.8: The Kotlin Playground
The Playground site also includes a bunch of examples and exercises to
familiarize the developer with major Kotlin features. The exercises, also
known as Kotlin koans, take a form of failing test cases which must be
fixed in order to pass (Figure 1.9):
Figure 1.9: Kotlin Koans
We strongly recommend going through these examples as a valuable
complement to the book itself.
Kotlin support is also available in popular data science notebooks such as
Jupyter and Apache Zeppelin. These notebooks provide an interactive code
editor where you can execute commands on the fly and see their results.
They come very handy in data science and machine learning applications,
especially in the context of visualization and exploratory research.
Apache Zeppelin, in particular, comes with a bundled Kotlin plugin starting
from 0.9.0.
Jupyter plugin, on the hand, must be installed manually (as explained in
https://github.com/Kotlin/kotlin-jupyter ReadMe).
Setting up an Eclipse project
Kotlin tooling is not limited to IntelliJ. Thanks to the Eclipse plugin, the
developers who prefer that IDE can use Kotlin as well. Although language
support in Eclipse is not as extensive as IntelliJ’s, it still provides a lot of
code assistance features for the developer’s benefit such as code
highlighting, completion, program execution and debugging, basic
refactorings, and more.
If you don’t have Eclipse, it can be freely downloaded at
www.eclipse.org/downloads. After running the installer, choose “Eclipse
IDE for Java Developers (or “Enterprise Java Developers”) and follow
the instructions. For that tutorial, we’ve used Eclipse 4.18 released in
December of 2020.
Unlike IntelliJ IDEA, Eclipse doesn’t come with bundled Kotlin support
meaning that the plugin must be installed from the Eclipse Marketplace
before we can get to writing the code. To do that, select Help | Eclipse
Marketplace and search for the Kotlin plugin (Figure 1.10).
After you click on the Install button, the IDE will download and install
the plugin. Make sure to accept license agreements and restart Eclipse in
order to complete the installation.
Figure 1.10: Installing Kotlin plugin from Eclipse Marketplace
Now, we can get to setting up a project. First, we switch IDE to Kotlin
perspective using the Window | Perspective | Open Perspective |
Other command and choose Kotlin in the dialog box that follows. Apart
from the layout change, this perspective makes some Kotlin actions
accessible directly from the application menu. So in order to create a
project, we need to choose File | New | Kotlin Project to specify a
new project name and click on Finish (Figure 1.11).
Figure 1.11: Creating Koltin project
We’re almost there! By expanding the KotlinVerse node in the Package
Explorer view, you can see the components of our newly created project.
The Java Runtime Environment (JRE) library, the Kotlin Standard Library
and, as of yet empty, the src directory where the source files are kept. Now,
let’s create our first Kotlin file. Right-click on the src directory and choose
New | Kotlin File. Type the file name and click on Finish (Figure 1.12):
Figure 1.12: Creating Kotlin file
Eclipse automatically opens a new file in the editor window. Let’s type
“Hello, World” program you can recognize from our earlier example
(Figure 1.13):
Figure 1.13: "Hello, World" in Eclipse
That’s it! To run the program, you may use the Run | Run command:
Eclipse will compile your file to the JVM bytecode, start resulting program
and redirect its output to the Console view.
Conclusion
In this chapter, we learned the major aspects of Kotlin language such as
safety, conciseness, and support of functional and object-oriented
programming paradigms. Together with support of multiple development
platforms such as JVM, Android, JavaScript, and native applications, well-
designed interoperability with Java or other platform-specific code,
extensive ecosystem of tools, libraries and frameworks and fast-growing
community makes Kotlin an excellent language definitely worth learning.
We also looked at common tools you can use for getting started with Kotlin
programming, including IntelliJ IDEA, Eclipse IDE, and Kotlin
Playground. Now, we are ready to move ahead. In the next chapter, we’ll
focus on the anatomy of some basic syntactic structures like variables and
expressions as well as get acquainted with basic Kotlin types.
Points to remember
Kotlin is a multiparadigm and multiplatform language with a focus on
safety, conciseness, and interoperability.
Kotlin has an extensive IDE support (mainly provided by the IntelliJ
plugin).
Kotlin has a large ecosystem covering virtually all aspects of
development process.
Questions
1. Explain the meaning of the basic principles underlying the design of
Kotlin language.
2. List Kotlin project setup steps for IntelliJ IDEA and Eclipse IDEs.
3. What interactive editors are available for working with Kotlin code?
4. Describe major libraries and frameworks comprising the Kotlin
ecosystem.
CHAPTER 2
Language Fundamentals
In this chapter, you’ll learn the basic syntactic elements of the Kotlin
program and how to define and use variables. You’ll get an understanding
of Kotlin types which are used to represent numeric, character, and boolean
values as well as their built-in operations and get acquainted with more
complex structures such as strings and arrays. Along the way, we’ll also
point out major differences from the Java syntax and type system which
should ease the migration to Kotlin.
Structure
Basic syntax
Primitive types
Strings
Arrays
Objectives
Introduce the reader to the fundamentals of the Kotlin syntax such as
variables and expressions as well as built-in data structures represented by
strings and array types.
Basic syntax
We’ll start by explaining basic aspects of the Kotlin syntax such as rules
governing placement of comments, identifiers, and simple variable
definitions as well as building complex expressions from simple ones.
Comments
Like Java, Kotlin supports three varieties of comments that you can use to
document your code:
Single-line comments which start with // and continue till the end of
line.
Multi-line comments delimited by /* and */.
KDoc multi-line comments delimited by /** and */.
KDoc comments are used to generate rich text documentation similar to
Javadoc:
/*
multi-line comment
/* nested comment */
*/
println(“Hello”) // single-line comment
Java vs. Kotlin: Unlike Java, multi-line comments in Kotlin can be nested.
Defining a variable
The simplest form of a variable definition in Kotlin takes the following
form:
val timeInSeconds = 15
Let’s consider the elements which make it up:
The val keyword (from value)
The variable identifier which is a name you give to a new variable and
use it to refer to it later in the code
An expression which defines the variable’s initial value and follows
after the = sign
Java vs. Kotlin: You might’ve noticed that we didn’t put a semicolon (;) at
the end of the variable definition. This is not a mistake. In Kotlin, you can
omit the semicolon at the end of the line. In fact, this is a recommended
code style; putting one statement per line, you’ll virtually never need to use
semicolons in your code.
IDE Tips: IntelliJ enforces this code style by showing a warning for each
unnecessary semicolon.
Suppose we want to write a program which asks the user for two integer
numbers and outputs their sum. Here is how it might look like in Kotlin:
fun main() {
val a = readLine()!!.toInt()
val b = readLine()!!.toInt()
println(a + b)
}
Let’s look more closely at what it does:
1. readLine() is a call expression which tells the program to execute the
readLine, a standard Kotlin function which reads a single line from
the standard input and returns it as a character string.
2. !! is a not-null assertion operator which throws an exception if the
readLine() result is null. Unlike Java, Kotlin tracks if a type can
contain nulls and will not allow us to call the toInt() function unless
we make sure that nulls are ruled out. For now, we can simply ignore
it since readLine() never returns null when reading from the console.
In the next chapter, we’ll discuss the issue of the type nullability in
more detail.
3. We then call the toInt() function on the result of the readLine() call.
toInt is a method defined in the Kotlin’s String class which converts
the character string on which it’s called into the integer value. If the
string in question does not correspond to a valid integer, toInt() fails
with a runtime error which in this case just terminates our program.
For now, we won’t worry about that assuming that all user inputs are
valid and postpone the issue of error handling till the next chapter.
4. The result of the toInt() call is assigned to the variable a we define in
the same line.
5. Similarly, we define the second variable b which is assigned an integer
entered on the second line.
6. Finally, we compute the sum of two integers, a + b, and pass the
result to the println() function call which prints it to the standard
output.
The preceding variables that we have introduced are called local since
they’re defined in the body of a function (in our case, it’s main()). Apart
from that, Kotlin allows definition of properties which are similar to
Another Random Document on
Scribd Without Any Related Topics
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
This website includes information about Project Gutenberg™,
including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Learn Kotlin and Build Robust Android Apps with Bcoder.pdf
PDF
Why Use Kotlin for Android App Development-Here’s a Guide.pdf
PPTX
Android with kotlin course
PPTX
Android Development with Kotlin course
PDF
What is Kotlin.pdf
PDF
What Is Kotlin and Why Use It For App Development? - 2023 Guide
PDF
A Review Paper on Kotlin Programming Language
PPTX
Is kotlin better option for android app development
Learn Kotlin and Build Robust Android Apps with Bcoder.pdf
Why Use Kotlin for Android App Development-Here’s a Guide.pdf
Android with kotlin course
Android Development with Kotlin course
What is Kotlin.pdf
What Is Kotlin and Why Use It For App Development? - 2023 Guide
A Review Paper on Kotlin Programming Language
Is kotlin better option for android app development

Similar to Kotlin Indepth A Guide To A Multipurpose Programming Language For Serverside Frontend Android And Multiplatform Mobile Aleksei Sedunov (20)

PDF
Kotlin - A Beginner’s Guide__________________
PDF
Kotlin App Development Tips.pdf
PDF
Kotlin Programming Concise Expressive And Powerful Theophilus Edet
PDF
Why You Should Go with Kotlin for Android App Development.pdf
PDF
How to Find the Best Kotlin Development Company.pdf
PDF
Kotlin vs Java: Choosing The Right Language
PDF
Kotlin vs Java: Which is Better for Android App Development?
PDF
Flutter or Kotlin: Which Framework Reigns Supreme for App Development?
PDF
Should Kotlin be the preferred choice for Android App Development?
PPTX
Kotlin vs flutter which is better for doing business
PDF
Top Object-Oriented Programming Languages To Follow In December 2022.pdf
DOCX
Cs 6611 mad lab manual
DOCX
CS6611 Mobile Application Development Laboratory
PDF
Java As A Programming Language
PDF
The Concept Of Abstract Data Types
PDF
The Rise of Kotlin Ecosystem in the Android App Development Industry.pdf
PDF
Mobile App Development Company in Noida - Drona Infotech
PPTX
8 Reasons to Pick Kotlin Over Java for Android Development.pptx
PDF
Advantages of Kotlin for Android App Development
PDF
How Kotlin Has Improved The Quality Of Android App Development.pdf
Kotlin - A Beginner’s Guide__________________
Kotlin App Development Tips.pdf
Kotlin Programming Concise Expressive And Powerful Theophilus Edet
Why You Should Go with Kotlin for Android App Development.pdf
How to Find the Best Kotlin Development Company.pdf
Kotlin vs Java: Choosing The Right Language
Kotlin vs Java: Which is Better for Android App Development?
Flutter or Kotlin: Which Framework Reigns Supreme for App Development?
Should Kotlin be the preferred choice for Android App Development?
Kotlin vs flutter which is better for doing business
Top Object-Oriented Programming Languages To Follow In December 2022.pdf
Cs 6611 mad lab manual
CS6611 Mobile Application Development Laboratory
Java As A Programming Language
The Concept Of Abstract Data Types
The Rise of Kotlin Ecosystem in the Android App Development Industry.pdf
Mobile App Development Company in Noida - Drona Infotech
8 Reasons to Pick Kotlin Over Java for Android Development.pptx
Advantages of Kotlin for Android App Development
How Kotlin Has Improved The Quality Of Android App Development.pdf
Ad

Recently uploaded (20)

PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
RMMM.pdf make it easy to upload and study
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Classroom Observation Tools for Teachers
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
01-Introduction-to-Information-Management.pdf
PPTX
master seminar digital applications in india
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
RMMM.pdf make it easy to upload and study
Abdominal Access Techniques with Prof. Dr. R K Mishra
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Pharma ospi slides which help in ospi learning
VCE English Exam - Section C Student Revision Booklet
Classroom Observation Tools for Teachers
Supply Chain Operations Speaking Notes -ICLT Program
202450812 BayCHI UCSC-SV 20250812 v17.pptx
O7-L3 Supply Chain Operations - ICLT Program
01-Introduction-to-Information-Management.pdf
master seminar digital applications in india
2.FourierTransform-ShortQuestionswithAnswers.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Ad

Kotlin Indepth A Guide To A Multipurpose Programming Language For Serverside Frontend Android And Multiplatform Mobile Aleksei Sedunov

  • 1. Kotlin Indepth A Guide To A Multipurpose Programming Language For Serverside Frontend Android And Multiplatform Mobile Aleksei Sedunov download https://ebookbell.com/product/kotlin-indepth-a-guide-to-a- multipurpose-programming-language-for-serverside-frontend- android-and-multiplatform-mobile-aleksei-sedunov-43887986 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Kotlin Indepth Volii A Comprehensive Guide To Modern Multiparadigm Language Aleksei Sedunov https://ebookbell.com/product/kotlin-indepth-volii-a-comprehensive- guide-to-modern-multiparadigm-language-aleksei-sedunov-44848948 Kotlin Indepth Voli A Comprehensive Guide To Modern Multiparadigm Language Aleksei Sedunov https://ebookbell.com/product/kotlin-indepth-voli-a-comprehensive- guide-to-modern-multiparadigm-language-aleksei-sedunov-44848972 Kotlin Indepth Vol I A Comprehensive Guide To Modern Multiparadigm Language Aleksei Sedunov https://ebookbell.com/product/kotlin-indepth-vol-i-a-comprehensive- guide-to-modern-multiparadigm-language-aleksei-sedunov-44859406 Pro Spring Boot 3 With Kotlin Indepth Guide To Best Practices For Cloudnative And Microservices Development 3rd Edition Peter Spth https://ebookbell.com/product/pro-spring-boot-3-with-kotlin-indepth- guide-to-best-practices-for-cloudnative-and-microservices- development-3rd-edition-peter-spth-231835744
  • 3. Pro Spring Boot 3 With Kotlin Indepth Guide To Best Practices For Cloudnative And Microservices Development 3rd Edition Peter Spth https://ebookbell.com/product/pro-spring-boot-3-with-kotlin-indepth- guide-to-best-practices-for-cloudnative-and-microservices- development-3rd-edition-peter-spth-231835754 Pro Spring 6 With Kotlin An Indepth Guide To Using Kotlin Apis In Spring Framework 6 1st Edition Peter Spth https://ebookbell.com/product/pro-spring-6-with-kotlin-an-indepth- guide-to-using-kotlin-apis-in-spring-framework-6-1st-edition-peter- spth-52328224 Programming Kotlin Familiarize Yourself With All Of Kotlins Features With This Indepth Guide Stephen Samuel https://ebookbell.com/product/programming-kotlin-familiarize-yourself- with-all-of-kotlins-features-with-this-indepth-guide-stephen- samuel-22009530 Kotlin In Action Second Edition Meap V09 Chapters 1 To 10 Of 16 Svetlana Isakova https://ebookbell.com/product/kotlin-in-action-second-edition- meap-v09-chapters-1-to-10-of-16-svetlana-isakova-50703078 Kotlin In Action Dmitry Jemerov Svetlana Isakova https://ebookbell.com/product/kotlin-in-action-dmitry-jemerov- svetlana-isakova-7032742
  • 7. Kotlin In-Depth A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile Aleksei Sedunov www.bpbonline.com
  • 8. FIRST EDITION 2022 Copyright © BPB Publications, India ISBN: 978-93-91030-63-6 All Rights Reserved. No part of this publication may be reproduced, distributed or transmitted in any form or by any means or stored in a database or retrieval system, without the prior written permission of the publisher with the exception to the program listings which may be entered, stored and executed in a computer system, but they can not be reproduced by the means of publication, photocopy, recording, or by any electronic and mechanical means. LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY The information contained in this book is true to correct and the best of author’s and publisher’s knowledge. The author has made every effort to ensure the accuracy of these publications, but publisher cannot be held responsible for any loss or damage arising from any information in this book. All trademarks referred to in the book are acknowledged as properties of their respective owners but BPB Publications cannot guarantee the accuracy of this information. www.bpbonline.com
  • 9. Dedicated to Tatiana, my guiding light and the incessant source of inspiration
  • 10. About the Author Aleksei Sedunov has been working as a Java developer since 2008. After joining JetBrains in 2012, he’s been actively participating in the Kotlin language development focusing on IDE tooling for the IntelliJ platform. Currently, he’s working in a DataGrip team, a JetBrains Database IDE, carrying on with using Kotlin as the main development tool.
  • 11. About the Reviewers Sanjay Kakadiya is currently working as a Sr Software developer of the e- commerce Android app. He completed his Bachelor of Engineering in IT from Gujarat University in 2012 and has more than 9 years of experience in mobile application development using Java, React Native, and Kotlin. He has been a co-organizer of the Ahmedabad Web and Mobile Developers Meetup group since 2015. He is a Kotlin and Java addict. He is obsessed with the elegant and functional style code. He mainly focuses on the mobile apps architecture. Sanjay has created and improvised dozens of successful applications for clients in areas of social networking, education, video streaming, entertainment, self-help, fitness, lifestyle, and commerce. Touhidul Islam is currently working as a mobile engineer at Toptal. He has a good grasp at data structure and algorithms and an eye for better architecture. Although, he has professional software experience in both cross-platform mobile and back-end technologies, he shines on native Android development. He has hands-on experience working at startups from his early career and one of the software developed by him earns about 40% of the revenue for that company. He later joined a big tech company developing pixel-perfect customer-facing mobile software and led the development there. He is currently working with Australia’s one of the leading service provider companies to revolutionize how people interact with service providers.
  • 12. Acknowledgements Above all others, I would like to give my gratitude to the entire Kotlin team at JetBrains which has created such a beautiful language and continues to relentlessly work on its improvement – especially Andrey Breslav who’s been leading the language design from the very first day. I’m really grateful to everyone at BPB Publications for giving me this splendid opportunity for writing this book and lending a tremendous support in improving the text before it gets to the readers. Many thanks to Sanjay Kakadiya and Touhidul Islam for their great help as technical reviewers for the second edition. Last but not least, I’d like to thank my beloved family for their support throughout the work on the book.
  • 13. Preface Since its first release in 2016 (and even long before that), Kotlin has been gaining popularity as a powerful and flexible tool in a multitude of development tasks being equally well-equipped for dealing with mobile, desktop, and server-side applications and finally, getting its official acknowledgment from Google in 2017 and 2018 as a primary language for Android development. This popularity is well-justified since language pragmatism, the tendency to choose the best practice among known solutions was one of the guiding principles of its design. With the book you’re holding in your hands, I’d like to invite you to the beautiful world of Kotlin programming where you can see its benefits for yourself. After completing this book, you’ll have all the necessary knowledge to write in Kotlin on your own. The first volume deals with the fundamentals of Kotlin language such as its basic syntax, procedural, object-oriented, and functional programming aspects as well as the Kotlin Standard Library. The book is divided into 9 chapters as follows: Chapter 1 explains key ideas behind the language design, gives an overview of the Kotlin ecosystem and tooling, and guides the reader through the first steps required to set up a Kotlin project in various environments. Chapter 2 introduces the reader to the Kotlin syntax, explains how to use variables, and describes simple data types such as integers or Boolean values as well as their built-in operations. It also addresses the basics of more complex data structures such as strings and arrays. Chapter 3 discusses the syntax of Kotlin functions and explains the uses of various control structures supported by Kotlin such as binary/multiple choice, iteration, and error handling. Additionally, it addresses the matter of using packages for code structuring. Chapter 4 introduces the reader to the basic aspects of object-oriented programming in Kotlin. It explains how to create and initialize a class instance and how to control member access, describe the use of object
  • 14. declarations and non-trivial kinds of properties, and brings up the concept of type nullability. Chapter 5 explains the functional aspects of Kotlin and introduces the reader to the idea of higher-order and anonymous functions, addresses the uses of inline functions, and explains how one can add features to existing types using extension functions and properties. Chapter 6 explains the use of special kinds of classes tailored at specific programming tasks: data classes for simple data holders, enumerations for representing a fixed set of instances, and inline classes for creating lightweight wrappers. Chapter 7 explores object-oriented features introduced in Chapters 4 and 6 focusing on the idea of a class hierarchy. It explains how to define subclasses, how to use abstract classes and interfaces, and how to restrict hierarchies using sealed classes. Chapter 8 describes a major part of the Kotlin standard library which is concerned with various collection types and their operations as well as utilities simplifying file access and stream-based I/O. Chapter 9 introduces the idea of generic declarations and explains how to define and use generic classes, functions, and properties in Kotlin. It also explains the notion of variance and how it can be used to improve flexibility of your generic code. The second volume introduces you to the more advanced Kotlin features such as reflection, domain-specific languages and coroutines, discusses Java/Kotlin interoperability issues, and explains how Kotlin can be used in various development areas, including testing, Android applications, and Web. It’s divided into the following 8 chapters: Chapter 10 addresses the use of annotations which allow you to accompany the Kotlin code with various metadata and explains the basics of Reflection API which provides access to runtime representation of Kotlin declarations. Chapter 11 describes some advanced features which help developer in composing flexible APIs in the form of the domain-specific languages: operator overloading, delegated properties, and builder-style DSLs based on the higher-order functions.
  • 15. Chapter 12 discusses common issues of combining Java and Kotlin code within the same codebase and explains the specifics of using Java declarations in Kotlin code and vice versa. Chapter 13 introduces the reader to the Kotlin coroutines library which introduces a set of building blocks for programming asynchronous computations. Additionally, it describes some utilities simplifying the use of Java concurrency API in Kotlin code. Chapter 14 discusses the KotlinTest, a popular testing framework aimed specifically at the Kotlin developers. It describes various specification styles, explains the use of assertion API, and addresses more advanced issues like using fixtures and test configurations. Chapter 15 serves as an introduction to using Kotlin for development on the Android platform. It guides the reader through setting up an Android Studio project and explains basic aspects of Android development using an example of a simple calculator application. Chapter 16 explains the basic features of the Ktor framework aimed at development of connected applications which make heavy use of Kotlin features and asynchronous computations. Chapter 17 describes how to build a microservice application using Spring Boot and Ktor frameworks.
  • 16. Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/04dc29 The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/Kotlin-In-Depth. In case there's an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family. Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.com and as a print book
  • 17. customer, you are entitled to a discount on the eBook copy. Get in touch with us at: business@bpbonline.com for more details. At www.bpbonline.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 BPB books and eBooks.
  • 18. 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 business@bpbonline.com 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 www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights 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. Reviews 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 BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com.
  • 19. Table of Contents 1. Kotlin - Powerful and Pragmatic Structure Objectives What is Kotlin? Safe Multiparadigm Concise and expressive Interoperable Multiplatform Kotlin ecosystem Coroutines Testing frameworks Android development Web development Desktop applications Getting started with Kotlin Setting up an IntelliJ project Using REPL Interactive editors Setting up an Eclipse project Conclusion Points to remember Questions 2. Language Fundamentals Structure Objectives Basic syntax Comments Defining a variable Identifiers Mutable variables
  • 20. Expressions and operators Primitive types Integer types Floating-point types Arithmetic operations Bitwise operations Char type Numeric conversions Boolean type and logical operations Comparison and equality Strings String templates Basic string operations Arrays Constructing an array Using arrays Conclusion Points to remember Multiple choice questions Answers Questions 3. Defining Functions Structure Objective Functions Function anatomy Trailing commas Positional vs named arguments Overloading and default values Varargs Function scope and visibility Packages and imports Packages and directory structure Using import directives Conditionals Making decisions with if statements
  • 21. Ranges, progressions, and in operation when statements and multiple choice Loops while/do-while loop Iterables and for loop Changing loop control-flow: break and continue Nested loops and labels Tail-recursive functions Exception handling Throwing an exception Handling errors with try statements Conclusion Points to remember Multiple choice questions Answers Questions Key terms 4. Working with Classes and Objects Structure Objectives Defining a class A class anatomy Constructors Member visibility Nested classes Local classes Nullability Nullable types Nullability and smart casts Not-null assertion operator Safe call operator Elvis operator Properties: Beyond simple variables Top-level properties Late initialization Using custom accessors
  • 22. Lazy properties and delegates Objects and companions Object declarations Companion objects Object expressions Conclusion Points to remember Multiple choice questions Answers Questions Key terms 5. Leveraging Advanced Functions and Functional Programming Structure Objective Functional programming in Kotlin Higher-order functions Functional types Lambdas and anonymous functions Callable references Inline functions and properties Non-local control flow Extensions Extension functions Extension properties Companion extensions Lambdas and functional types with the receiver Callable references with receiver Scope functions run / with run without context let apply / also Extensions as class members Conclusion Points to remember Questions
  • 23. Key terms 6. Using Special-Case Classes Structure Objective Enum classes Exhaustive when expressions Declaring enums with custom members Using common members of enum classes Data classes Data classes and their operations Destructuring declarations Inline classes Defining an inline class Unsigned integers Conclusion Points to remember Questions Key terms 7. Exploring Collections and I/O Structure Objective Collections Collection types Iterables Collections, lists, and sets Sequences Maps Comparables and comparators Creating a collection Basic operations Accessing collection elements Collective conditions Aggregation Filtering Transformation
  • 24. Extracting subcollections Ordering Files and I/O streams Stream utilities Creating streams URL utilities Accessing file content File system utilities Conclusion Points to remember Multiple choice questions Answers Questions 8. Understanding Class Hierarchies Structure Objective Inheritance Declaring a subclass Subclass initialization Type Checking and Casts Common methods Abstract classes and interfaces Abstract classes and members Interfaces Sealed classes Delegation Conclusion Points to remember Multiple choice questions Answers Questions 9. Generics Structure Objective Type parameters
  • 25. Generic declarations Bounds and constraints Type erasure and reification Variance Variance: Distinguishing producers and consumers Variance at the declaration site Use-site variance with projections Star projections Type aliases Conclusion Points to remember Questions 10. Annotations and Reflection Structure Objectives Annotations Defining and using annotation classes Built-in annotations Reflection Reflection API overview Classifiers and types Callables Conclusion Questions 11. Domain-Specific Languages Structure Objective Operator overloading Unary operations Increments and decrements Binary operations Infix operations Assignments Invocations and indexing Destructuring
  • 26. Iteration Delegated properties Standard delegates Creating custom delegates Delegate representation Higher-order functions and DSLs Fluent DSL with infix functions Using type-safe builders @DslMarker Conclusion Questions 12. Java Interoperability Structure Objective Using Java code from Kotlin Java methods and fields Unit vs void Operator conventions Synthetic properties Platform types Nullability annotations Java/Kotlin type mapping Single abstract method interfaces Working with Java records Using the Java-to-Kotlin converter Using the Kotlin code from Java Accessing properties File facades and top-level declarations Objects and static members Changing the exposed declaration name Generating overloads Declaring exceptions Inline functions Type aliases Exposing Kotlin classes as Java records Conclusion
  • 27. Questions 13. Concurrency Structure Objective Coroutines Coroutines and suspending functions Coroutine builders Coroutine scopes and structured concurrency Coroutine context Coroutine control-flow Job lifecycle Cancellation Timeouts Coroutine dispatching Exception handling Concurrent communication Channels Producers Tickers Flows Actors Using Java concurrency Starting a thread Synchronization and locks Coroutine debugger Conclusion Questions 14. Testing with Kotlin Structure Objective KotlinTest specifications Getting started with KotlinTest Specification styles Assertions Matchers
  • 28. Inspectors Handling exceptions Testing non-deterministic code Property-based testing Fixtures and configurations Providing a fixture Test configuration Conclusion Questions 15. Android Applications Structure Objective Getting started with Android Setting up an Android Studio project Gradle build scripts Activity Using an emulator Activities Designing an application UI Implementing an activity class View binding Preserving the activity state Conclusion Questions 16. Web Development with Ktor Structure Objective Introducing Ktor Server features Routing DSL Handling calls HTML DSL Sessions support Client features Requests and responses
  • 29. Cookies Conclusion Questions 17. Building Microservices Structure Objectives The microservice architecture Introducing Spring Boot Setting up a project Deciding on the Services API Implementing a random generator service Implementing a password generator service Microservices with Ktor Using the JSON serialization feature Implementing a password generator service Conclusion Questions Index
  • 30. CHAPTER 1 Kotlin - Powerful and Pragmatic This chapter is meant to explain the major features which make Kotlin an excellent and efficient language for modern application development and the reasons why you might want to learn it. We’ll learn the basic ideas which stand behind the Kotlin design and get an overview of Kotlin libraries and frameworks for different application areas such as Android applications, concurrency, testing and web development. In conclusion, we’ll guide you through the steps required to set up a Kotlin project in two popular development environments, IntelliJ IDEA and Eclipse, and introduce you to the interactive Kotlin shell. Structure We will cover the following topics: What is Kotlin? Major components of the Kotlin ecosystem Setting up a Kotlin project in IDE and online editors Objectives At the end of the chapter, you’ll get an understanding of the basic Kotlin principles and the Kotlin ecosystem as well as what simple a Kotlin program looks like and you will be able to set up a project in common IDEs. What is Kotlin? Kotlin is a multiplatform and multiparadigm programming language emphasizing safety, conciseness, and interoperability. Conceived in late 2010, it had reached its first release in February 2016 and has been steadily becoming an increasingly popular and promising tool in many development
  • 31. areas such as Android development, desktop applications, or server-side solutions. The company which stands behind the language and has been investing in its development ever since is JetBrains which is famous for its excellent software engineering tools such as IntelliJ IDEA. By August 2020, Kotlin had reached version 1.4, acquiring massive community, well- developed ecosystems, and extensive tooling. Having overgrown an original intent of creating a better Java alternative, it now embraces multiple platforms, including Java Virtual Machine, Android, JavaScript, and native applications. In 2017, Google announced Kotlin an officially supported language of the Android platform which gave a tremendous boost to the language popularity. Nowadays, a lot of companies – among them Google, Amazon, Netflix, Pinterest, Uber, and many others – are using Koltin for production development, and the number of open positions for Kotlin developers is growing steadfast. It all became possible thanks to the efforts devoted to the careful language design and putting into action the primary traits which make Kotlin such an excellent development tool. The language philosophy has mainly arisen based on the problems it was intended to solve back in 2010. By that time, JetBrains had already accumulated an extensive Java code base for products centered around its IntelliJ platform which was arguably the most known IntelliJ IDEA, had also included a set of minor IDEs dedicated to different technologies such as WebStorm, PhpStorm, RubyMine, etc. The maintenance and growth of such codebase, however, was being hampered by Java itself due to its slow evolution and lack of many useful features which at that moment had already been available in such languages as Scala and C#. Having researched the JVM languages available at that moment, the company concluded that no existing language proved satisfiable for their needs and decided to invest resources into implementation of their own language. The new language was eventually named Kotlin as a tribute to an island near Saint-Peteresburg, Russia where most of its development team was located. So what are those traits which have been shaping the language from the very beginning? In fact, we’ve already given the answer in its definition. The reason behind Kotlin is a need for a multiparadigm language emphasizing safety, conciseness, and interoperability. Let’s look at these traits in more detail.
  • 32. Safe For a programming language, being safe means being able to prevent a programmer’s errors. In practice, designing the language with respect to safety is a matter of tradeoff since error prevention typically comes at a cost. You give the compiler more detailed information about your program or allow it to spend more time reasoning about it correctness (probably both). One of Kotlin design goals was to find a sort of golden mean; contriving a language with more stronger safety guarantees than Java, but not so strong to frustrate a developer’s productivity. And although the Kotlin solution is by no means absolute, it has repeatedly proved to be an efficient choice in practice. We’ll discuss various aspects of Kotlin safety as we go through the book. Here, we’d like to point out some major features: Type inference which allows the developer to omit explicit declaration types in most cases (Java 10 introduced this for local variables) Nullable types regulate the usage of null and help to prevent infamous NullPointerException Smart casts which simplify type casting reducing the chance of casting errors at runtime Multiparadigm Initially, the meaning behind Kotlin multiparadigmality implied the support of functional programming in addition to the conventional object-oriented paradigm typical for many mainstream programming languages such as Java. The functional programming is based around the idea of using functions as values: passing them as parameters or returning from other functions, declaring locally, storing in variables, etc. Another aspect of the functional paradigm is an idea of immutability which means that objects you manipulate can’t change their state once created and functions can’t produce side effects. The major benefit of this approach is improved programming flexibility. Being able to create a new kind of abstraction, you can write more expressive and concise code, thus increasing your productivity. Note that although functional programming principles can be employed in many
  • 33. languages (Java’s anonymous classes, for example, were an obvious choice before introduction of lambdas), not every language has necessary syntactic facilities encouraging the writing of such code. Kotlin, on the contrary, included necessary features right from the start. They include, in particular, functional types smoothly integrating functions into the language type systems and lambda expressions meant to create functionally-typed values from code blocks. The standard library as well as external frameworks provides an extensive API facilitating the functional style. Nowadays, many of that also apply to Java which had introduced functional programming support starting with Java 8. But its expressiveness still somewhat falls behind Kotlin’s. We’ll cover the basics of functional programming in Chapter 5, Leveraging Advanced Functions and Functional Programming, but its applications and examples will accompany us throughout the book. Over its growth, the language also began to exhibit two more programming paradigms. Thanks to the ability to design APIs in the form of domain- specific languages (DSLs) Kotlin can be used in a declarative style. In fact, many Kotlin frameworks provide their own DSLs for specific tasks with no need to sacrifice type-safety or expressive power of the general-purpose programming language. For example, the exposed framework includes a DSL for defining database schema and manipulating its data, whereas kotlinx.html gives a concise and type-safe alternative to HTML template languages. In Chapter 11, Domain-Specific Languages, we’ll discuss these examples in more detail as well as learn how to create our own DSLs. One more paradigm, namely, concurrent programming, entered the language with the introduction of coroutines. Although, concurrency support by itself is present in many languages, including Java, the Kotlin features a rich set of programming patterns which enable a new programming approach. We’ll cover the basics of this approach in Chapter 13, Concurrency. All in all, the presence of multiple paradigms greatly increases the language’s expressive power, making it a more flexible and multi-purposed tool. Concise and expressive
  • 34. Developer productivity is largely tied with the ability to quickly read and understand the code, be it some other developer’s work or maybe your own after a significant time has passed. In order to understand what a specific piece of code does, you need to also understand how it’s related to other parts of your program. That’s why reading the existing code generally takes more time than writing a new one and that’s why language conciseness and the ability to clearly express a programmer’s intents without much information noise is a crucial aspect of language efficiency as a development tool. The designers of Kotlin did their best to make language as concise as possible, eliminating a lot of notorious Java boilerplate such as field getters and setters, anonymous classes, explicit delegation, and so on. On the other hand, they made sure the conciseness is not overtly abused – unlike Scala; for example, Kotlin doesn’t allow the programmer to define custom operators, but only redefine existing ones since the former tends to obfuscate the operation meaning. In the course of the book, we’ll see numerous implications of this decision and how useful it turned to be. Another aspect of Kotlin’s conciseness is tightly related to the DSLs (see Chapter 11, Domain-Specific Languages which greatly simplify the description of specific programming domains with a minimum of syntactic noise. Interoperable Java interoperability was a major point in Kotlin design since the Kotlin code wasn’t mean to exist in isolation, but to cooperate as smoothly as possible with the existing codebase. That’s why Kotlin designers made sure that not only the existing Java code can be used from Kotlin, but that Kotlin code can also be used from Java with little to no effort. The language also includes a set features specifically meant to tune interoperability between Java and Kotlin. As the language overgrew, the JVM and spread to other platforms, interoperability guarantees were extended as well to cover interaction with JavaScript code for the JS platform and C/C++/Objective C/Swift code for native applications.
  • 35. We’ll devote Chapter 12, Java Interoperability, to discuss the Java interoperability issues and how Kotlin and Java can be mixed together in the same project. Multiplatform Multiplatformity wasn’t an original intent of Kotlin designers, but rather manifested itself as a result of language evolution and adaptation to the needs of the development community. While JVM and Android remain a primary target of Kotlin development, nowadays the supported platforms also cover the following: JavaScript, including browser and Node.js applications as well as JavaScript libraries Native applications and libraries for macOS, Linux and Windows Since 1.3 Kotlin supports multiplatform development with major uses cases being sharing the code between Android and iOS applications and creating multiplatform libraries for JVM/JS/Native world. Kotlin ecosystem Throughout its evolution, Kotlin has given rise to a rich set of libraries and frameworks covering most of software development aspects. Here, we will try to give you an overview of available tools which hopefully will serve as a guide in this ocean of possibilities. Note, however, that as the ecosystem is continuously growing, the state-of-the-art presented in this book at the moment that is being written will inevitably fall out of date, so don’t hesitate looking for it by yourself. A good starting point is a community- updated list of libraries and frameworks available on the Awesome Kotlin website at https://interlink. It’s also worth noting that thanks to well-conceived Java interoperability Kotlin applications may benefit from a whole lot of existing Java libraries. In some cases, they have specific Kotlin extensions allowing one to write more idiomatic code. Coroutines
  • 36. Thanks to the concept of suspendable computations, Kotlin is able to support concurrency-related programming patterns such as aync/await, futures, promises, and actors. The Coroutines framework provide a powerful, elegant, and easily scalable solution to concurrency problems in the Kotlin application whether it is a server-side, mobile, or desktop one. The major features of the coroutines include, among others: A lightweight alternative to threads Flexible thread dispatching mechanism Suspendable sequences an iterators Sharing memory via channels Using actors to share mutable state via message sending We’ll cover the basics of the coroutine API in Chapter 13, Concurrency, which deals with concurrency issues in Kotlin. Testing frameworks Apart from familiar Java testing frameworks such as JUnit, TestNG, and Mockito which can be with little effort employed in a Kotlin application, the developers can enjoy the power of Kotlin-tailored frameworks providing useful DSLs for testing purposes; be it test definitions or mocking your objects. In particular, we’d like to point out the following: Mockito-Kotlin, an extension for the popular Mockito framework simplifying object mocking in Kotlin. Spek, a behavior-driven testing framework supporting Jasmine- and Gherkin-styled definition of test cases. KotlinTest, a ScalaTest-inspired framework which supports flexible test definitions and assertions. In Chapter 14, Testing with Kotlin, we’ll pay more attention to the features provided by Spek and Mockito and consider how to use them in your projects. Android development
  • 37. Android is one of the major and most actively growing application areas of Kotlin. This has become especially relevant after Google’s announced the Kotlin a first-class Android language implying, in particular, that Android tooling is now being designed and developed with due regard to the Kotlin features as well. Apart from the excellent programming experience brought by the Android Studio plugin, Android developers can benefit from the smooth interoperability with many popular frameworks such as Dagger, ButterKnife, and DBFlow. Among Kotlin-specific Android tools, we’d like to pay attention to Anko and Kotlin Android Extensions: Kotlin Android Extensions is a compiler plugin whose main feature is data-binding which allows you to use XML-defined views as if they’re implicitly defined in your code, thus avoiding the infamous findViewById() calls. It supports view caching and the ability to automatically generate Parcelable implementations for user-defined classes. Thanks to this there is no need to employ external frameworks like ButterKnife in pure Kotlin projects. Anko is a Kotlin library which simplifies the development of Android applications. In addition to numerous helpers, it includes a domain- specific language (Anko Layouts) for composing dynamical layouts accompanied by the UI preview plugin for Android Studio as well database query DSL based around Android SQLite. We’ll cover some of these features in Chapter 15, Android Applications, which introduces the reader to Kotlin-powered Android development. Web development Web/Enterprise application developers can also benefit from using Kotlin. Popular frameworks such as Spring 5.0 and Vert.x 3.0 include Kotlin- specific extensions which allow you to use their functionality in more Kotlin-idiomatic way. You can employ pure Kotlin solutions using a variety of frameworks: Ktor a JetBrains framework for creating an asynchronous server and client applications. kotlinx.html a domain-specific language for building HTML documents.
  • 38. Kodein a dependency injection framework. We’ll discuss specifics of building web applications and microservices using Ktor and Spring in Chapter 16, Web Development with Ktor and Chapter 17, Building Microservices, respectively. Desktop applications Developers of desktop applications for the JVM platform can employ TornadoFX, a JavaFX-based framework. It provides helpful domain- specific languages for building GUI and style description via CSS, support FXML markup, and MVC/MVP architecture. It also comes with an IntelliJ plugin simplifying the generation of TornadoFX projects, views, and other components. Getting started with Kotlin Now, you should have an idea of the Kotlin ecosystem, and the only thing we need to discuss before we can start exploring the language is how to set up a working environment. Setting up an IntelliJ project Although Kotlin by itself, like most programming languages, is not tied to a particular IDE or text editor, the choice of development tools has a great impact on the developer’s productivity. As of now, the JetBrains IntelliJ platform provides the most powerful and comprehensive support of the Kotlin development lifecycle. Right from the start, Kotlin IDE has been developed in tight integration with the language itself which helps it to stay up-to-date with Kotlin changes. For these reasons, we recommend using it for your own projects and employ it for the examples in the book. Since IntelliJ IDEA 15 Kotlin support is bundled into the IDE distribution, you won’t need to install any external plugins to facilitate Kotlin development. For this book, we’ve been using IntelliJ IDEA 2020.3 released in the late December, 2020. If you don’t have an IDEA installed, you can download the latest version from www.jetbrains.com/idea/download and follow the installation instructions from https://www.jetbrains.com/help/idea/install-and-set-
  • 39. up-product.html. IDEA comes in two editions: Community which is free and open-source and Ultimate which is a commercial product. The major difference is that the Ultimate edition includes a set of features related to the development of web and enterprise applications as well as database tools. You can find a more detailed list of changes at the download page. For this book, we won’t need the Ultimate features, so IDEA Community is more than enough. If you haven’t opened a project in IntelliJ before, you’ll see a welcome screen on startup where you can click on the Create New Project option to go directly to the project wizard dialog box. Otherwise, IntelliJ opens the recently edited project(s); in this case, choose File | New | Project in the application menu. Project types are grouped into categories you can see in the left pane. The exact set of categories and projects depends on the plugin installed, but for now, we’re interested in the Kotlin category which is available out-of-the box thanks to the bundled Kotlin plugin. When you click on it, you’ll see the list of available project templates (Figure 1.1):
  • 40. Figure 1.1: New project wizard (step 1) As of version 1.4.21 (which we’ve used when writing this book), the Kotlin plugin supports creating of projects targeting JVM, JavaScript, native applications as well several cases of multiplatform projects such as mobile applications targeting both Android and iOS. The platform determines both the type of compiler artifacts (bytecode for the JVM, .js files for JavaScript, and platform-specific executables for Kotlin/Native) and a set of available dependencies your project can use; a project targeting JavaScript, for example, can’t access classes from the Java class library. As we go ahead, our primary interest will be the JVM applications, so for this example, we’ll choose the corresponding option in the JVM group. The wizard also allows you to choose a particular build system for automating common tasks related to the project lifecycle: compilation, testing, packaging, publication, and so on. Detailed treatment of a particular build system specifics goes beyond the scope of the book and has little effect on our code examples apart from the project file structure. So in this tutorial, we’ll just choose IntelliJ as the default option before proceeding with project creation. Besides that, you’ll need to provide the project name and location which is a root directory for the project-related content, including its source files. Note that IntelliJ suggests the location automatically based on the project name you’ve typed, but you can change it if necessary. Since our project targets the JVM platform, we also have to specify a default JDK to use for the project compilation. That would allow our project to use classes from the Java standard library as well as compile Java sources in mixed-language projects. In Chapter 12, Java Interoperability, we’ll cover such projects in more detail and also discuss how to introduce Kotlin support to the existing Java projects. We recommend using JDK 8 or higher. For this example, we’ve chosen the latest (as of the book’s writing) release version of Oracle OpenJDK 15. Usually, IntelliJ auto-detects the JDK installed on your machine, but if that doesn’t happen or none of preconfigured JDKs in the Project SDK list suit your purposes, you can add a new one by choosing Add JDK options specifying the path to some preinstalled JDK instance, or Download JDK to have IDE download one of the popular JDK implementations (such as OpenJDK or Corretto) for you.
  • 41. One more thing worth mentioning is a Kotlin runtime library the IntelliJ has preconfigured for our project. By default, the project will reference a library in the IDE plugin directory which means it’s upgraded automatically whenever you update the plugin itself. If you, however, want your project to depend on a particular version of Kotlin runtime, only updating it manually out of necessity, you may change that behavior. To do that, expand the Kotlin Runtime group, click on the Create button and choose the Copy to option specifying the directory name where the library needs to be kept. Clicking on the Next button will bring the second step of the project wizard where you can specify additional options such as minimum JVM version on which your application is supposed to run, a test framework, and a predefined template the IDE will use to generate the initial project structure (for example; a console or Ktor-based web application). The example of step 2 is shown in Figure 1.2: Figure 1.2: New project wizard (step 2) In the final step, click on the Finish button and you will get IntelliJ to generate and open an empty project. By default, IntelliJ presents it in a two- panel view: Project tool window on the left and the editor area occupying most of the remaining area. The editor is initially empty since we haven’t
  • 42. opened a single file yet, so we’ll first focus on the Project window and use it to create a new Kotlin file. If the Project tool window is absent, you can bring it by clicking on the Project button (usually, it’s on the left-hand side of the window border) or using the shortcut Alt+1 (Meta+1). The Project window shows the hierarchical structure of your project. Let’s expand the root nodes and see what it contains (Figure 1.3). Currently, we’re mostly interested in the following three items: src directory which serves as a content root containing project source files. out directory where the compiler puts the generated bytecode (absent initially but created automatically on project compilation). External Libraries which list all libraries the project depends on. Figure 1.3: Project structure tool window Now, right-click on the src/main/kotlin directory and select the New | Kotlin File/Class command. In the dialog box that follows, type a file name main.kt. Make sure that the Kind field is set to File and click on OK. You’ll see the Project window updated to show a new file which is at the
  • 43. same time opened in the editor. Note that Kotlin source files must have the .kt extension. At last, we’re ready to write an actual code. Let’s type the following in the editor window (Figure 1.3): fun main() { println(“Hello, KotlinVerse!”) } The preceding code defines the main function which serves as an entry- point for the Kotlin application. The function body consists of a single statement, a call to the standard library function println() writing its argument to the program’s standard output with a new line added at the end. Figure 1.4: “Hello, World“ program Java developers will surely recognize a similarity between this code and the following Java program: public class Main { public static void main(String[] args) { System.out.println(“Hello, World!”) } } In fact, JVM’s version of the Kotlin println() function is just a call to System.out.println(). Since the JVM entry-point must be a static class method, you might be wondering how the Kotlin application is started without defining a single class. The answer is that although we haven’t defined a class explicitly, the Kotlin compiler will create one behind the scenes, putting there the JVM’s entry-point which in turn would call our main() function. We’ll get back to these so called facade classes in Chapter 12, Java Interoperability because they constitute a major aspect of Kotlin/Java interoperability. Also, note that unlike the JVM entry-point which is supposed to take an array of command-line arguments as its parameter, our main() function has
  • 44. no parameters at all. This comes in handy for the cases when command-line arguments are not used. If necessary, however, you can still define the entry-point taking these arguments: fun main(args: Array<String>) { println(args) } Parameterless main() is in fact a comparatively recent feature introduced in Kotlin 1.3. In earlier language versions, the only acceptable entry point was the one taking the String<Array> argument just like its Java counterpart. This feature took further development in Kotlin 1.4 where the compiler produces a warning if the main() parameter is not really used in the function’s body (see Figure 1.5): Figure 1.5: Unused parameter in the main() function You might’ve noticed a small green triangle on the left-hand side of the main() definition. This line marker indicates that function main(), being an entry-point, is executable. Clicking on that marker brings up a menu which allows you to run or debug its code. Let’s choose the Run MainKt option and see what happens (Figure 1.6). MainKt, by the way, is the name of the compiler-generated facade class we mentioned earlier. On choosing the Run command, IntelliJ compiles our code and executes the program. The Run tool window which is opened on program startup gets automatically linked to its standard I/O streams serving as a built-in console. If you’ve done everything correctly, the program will print Hello, KotlinVerse to the console and terminate successfully.
  • 45. Figure 1.6: Running a program If you look inside the out directory, you will see the .class files generated by the Kotlin compiler from our source program. Congratulations! You now have an understanding of how to set up and run a Kotlin project in the IntelliJ IDEA environment, and you are ready to delve into the language fundamentals. KotlinVerse, here we go! Using REPL Kotlin plugin for IntelliJ provides an interactive shell which allows you to evaluate program instructions on-the-fly. This can be used for quick testing of your code or experimenting with library functions. It is also quite handy for those who are just learning the Kotlin language. This feature is called REPL. The meaning behind this name is “Read/Evaluate/Print Loop” because that’s what the shell does. The reading code the user has typed, evaluates it, prints the result (if any), and loops the whole thing over. In order to access the REPL, select Tools | Kotlin | Kotlin REPL. You can type the Kotlin code in the REPL window just like you do it in the editor. The major difference is that each piece of code is compiled and executed right after you enter it. Once the code is typed, you need to press Ctrl + Enter (Command + Return) telling the IDE to process your input. Let’s try it out with:
  • 46. println(“Hello from REPL”) As far as you can see, IntelliJ responds with printing “Hello from REPL” to the console which in this case is shared with the REPL window. The printing of the preceding string is in fact a side effect of the println() function which by itself doesn’t return any result to the calling program. If we, however, attempt to evaluate some expression which does have some meaningful result, the output is slightly different. Let’s try entering 1+2*3 (Figure 1.7): Figure 1.7: Kotlin REPL The REPL gives us the expression result which is 7. Note the difference in font and = icon as opposed to the println() example. This is to signify that 7 is an actual result of the code you’ve typed. To sum it up, we advise you to get acquainted with this tool and use it throughout the book (and beyond) to experiment with any features you feel necessary. Interactive editors Apart from the REPL shell available in IntelliJ, it’s worth mentioning a similar, but more powerful online tool which lies somewhere in between a REPL and a full-fledged IDE. The tool in question is the Kotlin Playground. To give it a try open https://play.kotlinlang.org in your browser (Figure 1.8). The Kotlin Playground is basically an online environment which allows you to explore the language with no need for an actual IDE yet having some of
  • 47. its intelligent features at your disposal, including code editor, syntax and error highlighting, code completion, and console program runner. Figure 1.8: The Kotlin Playground The Playground site also includes a bunch of examples and exercises to familiarize the developer with major Kotlin features. The exercises, also known as Kotlin koans, take a form of failing test cases which must be fixed in order to pass (Figure 1.9): Figure 1.9: Kotlin Koans We strongly recommend going through these examples as a valuable complement to the book itself. Kotlin support is also available in popular data science notebooks such as Jupyter and Apache Zeppelin. These notebooks provide an interactive code editor where you can execute commands on the fly and see their results.
  • 48. They come very handy in data science and machine learning applications, especially in the context of visualization and exploratory research. Apache Zeppelin, in particular, comes with a bundled Kotlin plugin starting from 0.9.0. Jupyter plugin, on the hand, must be installed manually (as explained in https://github.com/Kotlin/kotlin-jupyter ReadMe). Setting up an Eclipse project Kotlin tooling is not limited to IntelliJ. Thanks to the Eclipse plugin, the developers who prefer that IDE can use Kotlin as well. Although language support in Eclipse is not as extensive as IntelliJ’s, it still provides a lot of code assistance features for the developer’s benefit such as code highlighting, completion, program execution and debugging, basic refactorings, and more. If you don’t have Eclipse, it can be freely downloaded at www.eclipse.org/downloads. After running the installer, choose “Eclipse IDE for Java Developers (or “Enterprise Java Developers”) and follow the instructions. For that tutorial, we’ve used Eclipse 4.18 released in December of 2020. Unlike IntelliJ IDEA, Eclipse doesn’t come with bundled Kotlin support meaning that the plugin must be installed from the Eclipse Marketplace before we can get to writing the code. To do that, select Help | Eclipse Marketplace and search for the Kotlin plugin (Figure 1.10). After you click on the Install button, the IDE will download and install the plugin. Make sure to accept license agreements and restart Eclipse in order to complete the installation.
  • 49. Figure 1.10: Installing Kotlin plugin from Eclipse Marketplace Now, we can get to setting up a project. First, we switch IDE to Kotlin perspective using the Window | Perspective | Open Perspective | Other command and choose Kotlin in the dialog box that follows. Apart from the layout change, this perspective makes some Kotlin actions accessible directly from the application menu. So in order to create a project, we need to choose File | New | Kotlin Project to specify a new project name and click on Finish (Figure 1.11).
  • 50. Figure 1.11: Creating Koltin project We’re almost there! By expanding the KotlinVerse node in the Package Explorer view, you can see the components of our newly created project. The Java Runtime Environment (JRE) library, the Kotlin Standard Library and, as of yet empty, the src directory where the source files are kept. Now, let’s create our first Kotlin file. Right-click on the src directory and choose New | Kotlin File. Type the file name and click on Finish (Figure 1.12): Figure 1.12: Creating Kotlin file Eclipse automatically opens a new file in the editor window. Let’s type “Hello, World” program you can recognize from our earlier example (Figure 1.13): Figure 1.13: "Hello, World" in Eclipse That’s it! To run the program, you may use the Run | Run command: Eclipse will compile your file to the JVM bytecode, start resulting program and redirect its output to the Console view. Conclusion
  • 51. In this chapter, we learned the major aspects of Kotlin language such as safety, conciseness, and support of functional and object-oriented programming paradigms. Together with support of multiple development platforms such as JVM, Android, JavaScript, and native applications, well- designed interoperability with Java or other platform-specific code, extensive ecosystem of tools, libraries and frameworks and fast-growing community makes Kotlin an excellent language definitely worth learning. We also looked at common tools you can use for getting started with Kotlin programming, including IntelliJ IDEA, Eclipse IDE, and Kotlin Playground. Now, we are ready to move ahead. In the next chapter, we’ll focus on the anatomy of some basic syntactic structures like variables and expressions as well as get acquainted with basic Kotlin types. Points to remember Kotlin is a multiparadigm and multiplatform language with a focus on safety, conciseness, and interoperability. Kotlin has an extensive IDE support (mainly provided by the IntelliJ plugin). Kotlin has a large ecosystem covering virtually all aspects of development process. Questions 1. Explain the meaning of the basic principles underlying the design of Kotlin language. 2. List Kotlin project setup steps for IntelliJ IDEA and Eclipse IDEs. 3. What interactive editors are available for working with Kotlin code? 4. Describe major libraries and frameworks comprising the Kotlin ecosystem.
  • 52. CHAPTER 2 Language Fundamentals In this chapter, you’ll learn the basic syntactic elements of the Kotlin program and how to define and use variables. You’ll get an understanding of Kotlin types which are used to represent numeric, character, and boolean values as well as their built-in operations and get acquainted with more complex structures such as strings and arrays. Along the way, we’ll also point out major differences from the Java syntax and type system which should ease the migration to Kotlin. Structure Basic syntax Primitive types Strings Arrays Objectives Introduce the reader to the fundamentals of the Kotlin syntax such as variables and expressions as well as built-in data structures represented by strings and array types. Basic syntax We’ll start by explaining basic aspects of the Kotlin syntax such as rules governing placement of comments, identifiers, and simple variable definitions as well as building complex expressions from simple ones. Comments
  • 53. Like Java, Kotlin supports three varieties of comments that you can use to document your code: Single-line comments which start with // and continue till the end of line. Multi-line comments delimited by /* and */. KDoc multi-line comments delimited by /** and */. KDoc comments are used to generate rich text documentation similar to Javadoc: /* multi-line comment /* nested comment */ */ println(“Hello”) // single-line comment Java vs. Kotlin: Unlike Java, multi-line comments in Kotlin can be nested. Defining a variable The simplest form of a variable definition in Kotlin takes the following form: val timeInSeconds = 15 Let’s consider the elements which make it up: The val keyword (from value) The variable identifier which is a name you give to a new variable and use it to refer to it later in the code An expression which defines the variable’s initial value and follows after the = sign Java vs. Kotlin: You might’ve noticed that we didn’t put a semicolon (;) at the end of the variable definition. This is not a mistake. In Kotlin, you can omit the semicolon at the end of the line. In fact, this is a recommended code style; putting one statement per line, you’ll virtually never need to use semicolons in your code. IDE Tips: IntelliJ enforces this code style by showing a warning for each unnecessary semicolon.
  • 54. Suppose we want to write a program which asks the user for two integer numbers and outputs their sum. Here is how it might look like in Kotlin: fun main() { val a = readLine()!!.toInt() val b = readLine()!!.toInt() println(a + b) } Let’s look more closely at what it does: 1. readLine() is a call expression which tells the program to execute the readLine, a standard Kotlin function which reads a single line from the standard input and returns it as a character string. 2. !! is a not-null assertion operator which throws an exception if the readLine() result is null. Unlike Java, Kotlin tracks if a type can contain nulls and will not allow us to call the toInt() function unless we make sure that nulls are ruled out. For now, we can simply ignore it since readLine() never returns null when reading from the console. In the next chapter, we’ll discuss the issue of the type nullability in more detail. 3. We then call the toInt() function on the result of the readLine() call. toInt is a method defined in the Kotlin’s String class which converts the character string on which it’s called into the integer value. If the string in question does not correspond to a valid integer, toInt() fails with a runtime error which in this case just terminates our program. For now, we won’t worry about that assuming that all user inputs are valid and postpone the issue of error handling till the next chapter. 4. The result of the toInt() call is assigned to the variable a we define in the same line. 5. Similarly, we define the second variable b which is assigned an integer entered on the second line. 6. Finally, we compute the sum of two integers, a + b, and pass the result to the println() function call which prints it to the standard output. The preceding variables that we have introduced are called local since they’re defined in the body of a function (in our case, it’s main()). Apart from that, Kotlin allows definition of properties which are similar to
  • 55. Another Random Document on Scribd Without Any Related Topics
  • 56. Project Gutenberg™ eBooks are often created from several printed editions, all of which are confirmed as not protected by copyright in the U.S. unless a copyright notice is included. Thus, we do not necessarily keep eBooks in compliance with any particular paper edition. Most people start at our website which has the main PG search facility: www.gutenberg.org. This website includes information about Project Gutenberg™, including how to make donations to the Project Gutenberg Literary Archive Foundation, how to help produce our new eBooks, and how to subscribe to our email newsletter to hear about new eBooks.
  • 57. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com