KEMBAR78
Kotlin in A Nutshell Ebook | PDF | Class (Computer Programming) | Programming
0% found this document useful (0 votes)
188 views38 pages

Kotlin in A Nutshell Ebook

The document provides an introduction to the Kotlin programming language. It discusses getting started with Kotlin by installing IntelliJ IDEA and creating a "Hello World" project. It then covers basic Kotlin syntax including variables, string templates, ranges, control flow structures, functions, classes, objects, interfaces, and collections. It also discusses lambda expressions, higher-order functions, and scope functions. The document serves as a tutorial to help new Kotlin programmers learn the essential elements of the language.

Uploaded by

Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
188 views38 pages

Kotlin in A Nutshell Ebook

The document provides an introduction to the Kotlin programming language. It discusses getting started with Kotlin by installing IntelliJ IDEA and creating a "Hello World" project. It then covers basic Kotlin syntax including variables, string templates, ranges, control flow structures, functions, classes, objects, interfaces, and collections. It also discusses lambda expressions, higher-order functions, and scope functions. The document serves as a tutorial to help new Kotlin programmers learn the essential elements of the language.

Uploaded by

Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

TABLE OF CONTENTS

About me ...................................................................................................................................................... 3
Getting started .............................................................................................................................................. 4
What is kotlin ............................................................................................................................................ 4
What can I do with kotlin .......................................................................................................................... 4
Installing intellij IDEA for Kotlin ................................................................................................................ 4
Creating your HelloWorld project ............................................................................................................. 4
Basic syntax ................................................................................................................................................... 7
Variables ................................................................................................................................................... 7
Formatting strings with string templates ................................................................................................. 9
Ranges ....................................................................................................................................................... 9
Control Flow: if, when, for, while............................................................................................................ 10
If Expression ........................................................................................................................................ 10
When expression ................................................................................................................................ 11
For loop ............................................................................................................................................... 12
The while loop ..................................................................................................................................... 13
Functions ................................................................................................................................................. 13
Classes, objects, and interfaces .................................................................................................................. 16
Classes ..................................................................................................................................................... 16
Constructors ........................................................................................................................................ 16
Primary constructors........................................................................................................................... 16
Secondary constructors ...................................................................................................................... 17
Creating instances of classes............................................................................................................... 18
Inheritance .......................................................................................................................................... 18
Data classes ......................................................................................................................................... 19
Sealed classes: constrained hierarchies .............................................................................................. 20
Enum classes ....................................................................................................................................... 21
Objects .................................................................................................................................................... 22
Companion objects ............................................................................................................................. 23
Interfaces ................................................................................................................................................ 23
Collections in kotlin ..................................................................................................................................... 25
Arrays ...................................................................................................................................................... 25
Lists ......................................................................................................................................................... 27
Immutable Lists (read-only) ................................................................................................................ 27
Mutable Lists ....................................................................................................................................... 27
Sets .......................................................................................................................................................... 28
Maps ....................................................................................................................................................... 29
Lambda expressions and Higher-Order functions ...................................................................................... 31
Lambda expressions ................................................................................................................................ 31
Higher-Order functions ........................................................................................................................... 32
Scope Functions .......................................................................................................................................... 34
let ............................................................................................................................................................ 34
with ......................................................................................................................................................... 35
Run .......................................................................................................................................................... 35
apply........................................................................................................................................................ 36
also .......................................................................................................................................................... 36
Final thoughts ............................................................................................................................................. 37
About me

 My name is Musab Agab I am 24 years old from Sudan.


 I have been coding since 2014.
 I have a degree in Network Engineering but I never worked in
that field.
 Being a “Java guy” for over 3 years, it wasn’t easy for me to
switch to another language.
 However, seeing what kotlin cable of, I switched to kotlin and I
never looked back again.
 I love sharing knowledge with others; this is why I wrote this
book.
Getting started
What is kotlin
Kotlin is an open-source statically typed programming language developed by JetBrains, it has
been around 2011 and it has steadily increased the popularity ever since.

What can I do with kotlin


Kotlin can be used for server-side or client side in web and Android. It is the first-class language
on Android.

Installing intellij IDEA for Kotlin


Go to the download page of official Jetbrains website. Choose the Operating System and
download the community edition, follow the installation instructions to install it.

Creating your HelloWorld project


This is how IntelliJ interface looks like when you first open it, from the menu choose Create
New Project
On the next screen on ‘Additional libraries and Frameworks’ make sure the option Kotlin/JVM is
checked and click next.

Now give your project a name and change the project location if you want then click finish.
Once the project is created expand src folder and find main.kt file, on this file write a main()
function with a print statement to print the text ‘Hello world’.
The Kotlin compiler always will start executing the code from the main function, use the green
arrow or the keyboard shortcut Shfit+F10 to run the application. You should see the text ‘Hello
world’ printed.
Basic syntax
Variables
In kotlin you start declaring a variable with a keyword, and you may or may not specify the
variable type after the name because kotlin lets you omit variable type.
Let us create a variable name and assign it the value “John doe”, since we give it a String value
kotlin knows it is a String.
Otherwise, we can tell kotlin explicitly that it is a String by using the colon operator (:) and the
type String.

We can also create another variable age and give it an Int value 23, we can also specify the type
explicitly using the colon operator (:) and type Int.
There are two keywords to declare variables in Kotlin:

 val (from the word value):It creates an immutable variable. A variable declared with val
can’t be reassigned after it’s initialized. Just like a final variable in Java.

 var (from the world variable): It creates a mutable variable. The value of such a variable
can be changed after initialization.

Trying to reassign a new value to a val variable will result to an error, but you can reassign a var
variable multiple times:

As a best practice, declare all variables in Kotlin with the val keyword. Change it to var only if
necessary.

A val variable must be initialized only once and cannot be reassigned after that, but you can
give it a different value depending on a condition, if the compiler can ensure that only one of
the initialization statements will be executed:
Formatting strings with string templates

Sometimes you may want to inject a variable value inside a String; in Java, we can use string
concatenation like this for example: “Hello”+ name. However, in kotlin we have much more
cleaner and easier syntax using String templates.
String templates are String literals that contain embedded expressions, Kotlin allows you to
refer to local variables in string literals by putting the $ character in front of the variable name:

Ranges
A range is essentially just an interval between two values, usually numbers: a start and an end.
You write it using the .. operator:

You check if a number inside a specific range using the in operator, for example:

Ranges in Kotlin are closed or inclusive, meaning the second value is always a part of the range.
The most basic thing you can do with integer ranges is loop over all the value (see in the for
loop section).If you can iterate over all the values in a range, such a range is called a
progression.
If you want to skip some numbers, you can specify a step (by default 1), here we are declaring a
range with a step of two:
You can use downTo function to create a range with a step of -1:

Control Flow: if, when, for, while


If Expression
Kotlin does not have ternary operator (condition? Then : else), because the if statement works
as an expression by itself.
Traditional usage: If the condition is met, the code block surrounded by curly braces will be
executed otherwise it will just skip it.

With else: If the condition is not met, the else block will be executed instead of the if block:

As expression: The last statement of if or else block will be returned and can be assigned to
another variable.
When expression

The when expression replaces the switch statement in C-like languages, it is like a switch
statement but more powerful. In the simplest form, it looks like this:

when matches its argument against all branches sequentially until some branch condition is
satisfied, it can be used either as an expression or as a statement.

when can also be used as a replacement for an if-else chain, If no argument is supplied, the
branch conditions are simply boolean expressions:

We can also check a value for being in or !in a range or a collection:


It is widely used with sealed classes to enforce all branch possibilities are being covered, the
compiler will enforce you to write all possible branches values of the sealed classes:

For loop
Unlike Java and other languages There is no traditional for loop in Kotlin. In Kotlin, for loop is
used to iterate through ranges, arrays, maps and so on (anything that provides an iterator).

Example: Iterate Through a Range


It is also possible to iterate over numbers with an arbitrary step (not necessarily 1). This is done
via the step function:

We will cover iterating over collections in the collections section

The while loop


Kotlin has while and do-while loops and their syntax does not differ from the corresponding
loops in Java:

Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
Function declaration in kotlin starts with the fun keyword, followed by the function name,
followed by the parameter list in parentheses. The parameter type is written after its name.
The return type comes after the parameter list, separated from it by a colon.
The functions can be declared at the top level of a file; you don’t need to put it in a class
Let’s see an example: Here we are declaring a function called sum that have two Int parameters
a , b and return type of Int.
In the function body we have only one statement that return the sum of a and b

Let’s call the function from our main function and we pass the parameters 3,4 and we are
storing the return value in a variable called result.
Then we simply print the value of the variable result with a print statement.

You can simplify the previous function even further. Because its body consists of a single
expression, you can use that expression as the entire body of the function, removing the curly
braces, return type and return statement.
Such a function body is called an expression body

If a function is written with its body in curly braces, we say that this function has a block body.
If it returns an expression directly, it has an expression body.
You do not have to specify a return type for a function that returns nothing, you can simply
omit it, and such a functions have a return type of Unit it is like void in Java.

Function parameters can have default values, which are used when you skip the corresponding
argument:

When calling a function, you can name one or more of its arguments, this what is known as
named arguments:
Classes, objects, and interfaces

Kotlin’s classes and interfaces differ a little from their Java counterparts: for example, interfaces
can contain property declarations. Unlike in Java, Kotlin’s declarations are final and public by
default.

Classes
Classes in Kotlin are declared using the keyword class followed by the class name and curly
braces for the class body:

Constructors
Kotlin have two types of constructors:

 Primary constructors
 Secondary constructors
Primary constructors

A class in kotlin can have a primary constructor and one or more secondary constructor. The
primary constructor is a part of the class header; it goes after the class name. The primary
constructor cannot contain any code.
Example a class with a primary constructor:

If the primary constructor does not have any annotations or visibility modifiers, omit the
constructor keyword:
If you want to write an Initialization code for a class use initializer blocks using init keyword:
You can have multiple initializer blocks that will during an instance initialization, the initializer
blocks are executed in the same order as they appear in the class body:

In fact, for declaring properties and initializing them from the primary constructor, Kotlin has a
concise syntax: A property in a class can be either a val or var

Secondary constructors
The class can also declare secondary constructors, which are prefixed with constructor:
Creating instances of classes
To create an instance of a class, we call the constructor as if it were a regular function:

You can also declare functions inside a class:

Calling the methods is very straightforward using the instance of a class:

Inheritance
Inheritance is one of the key features of object-oriented programming. It allows user to create a new
class (derived class) from an existing class (base class).

By default, classes in kotlin are final that means you cannot inherit from them unless you mark it using
the open keyword:
To inherit from another class you can use the colon operator : followed by the class name:

Class methods are final by default and you cannot override them in a subclass unless you mark them as
open:

It worth mentioning that Kotlin does not support inheritance from multiple classes, multiple inheritance
is achieved in interfaces.

Data classes
We regularly create classes just to hold data. In Java we used write a lot of boilerplate method such as
equals, hashCode, and toString and include them in our classes.

Although Java IDEs can automate the generation of these methods, the boilerplate code I still present in
your codebase and you also have to maintain it.

The kotlin compiler take it a step further: it can auto generate these methods behind the scenes using
Data classes.

To create a data class just before your class declaration with the keyword data:
The compiler automatically derives the following members from all properties declared in the primary
constructor:

 equals() / hashCode() pair;


 toString() of the form "User(name=John, age=42)";
 componentN() functions corresponding to the properties in their order of declaration;
 copy() function

To keep the generated code consistent, data classes have to fulfill the following requirements:

 The primary constructor needs to have at least one parameter;


 All primary constructor parameters need to be marked as val or var;
 Data classes cannot be abstract, open, sealed or inner;
 (before 1.1) Data classes may only implement interfaces.

Sealed classes: constrained hierarchies


Sealed classes restricts the possibility of creating subclasses. Use a sealed class when a value can have
one of the types from a limited set, but cannot have any other type.

For example, an API call response can have only two states: success and failure that is a suitable
situation to create a sealed class.

To declare a sealed class, you put the sealed modifier before the name of the class:

All the direct subclasses (children) must be nested inside the superclass:
A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class
itself. A sealed class is abstract by itself, it cannot be instantiated directly.

Sealed classes can be used effectively with when to check all possible branches:

Even if someone added a new child to the ApiResponse sealed class and forget to add the when
statement’s branch the compiler can give us an error if a branch is not covered.

Enum classes

In Kotlin, as in many other programming languages, an enum is its own specialized type, indicating that
something has a number of possible values.

Create an enum class:

Just as in Java, enums aren’t lists of values: you can declare properties and methods on enum classes.
Here is how it works:
Enum constants use the same constructor and property declaration syntax as you saw earlier for regular
classes.

Using when for choosing the right enum value: Returns the corresponding string if the color equals the
enum constant:

Objects
First, let us talk about singletons because it will help us to understand objects in Kotlin.

Singleton is an object-oriented pattern where a class can have only one instance (object).

For example, you are working an application having SQL database backend. You want to create a
connection pool to access the database while reusing the same connection for all clients. For this, you
can create the connection through singleton class so that every client get the same connection.

Kotlin provides an easy way to create singletons using the object declaration feature. For
that, object keyword is used.

An object declaration can contain properties, methods and so on. However, they are not allowed to
have constructors (which makes sense).

The object keyword can also be used to create objects of an anonymous class known as anonymous
object. They are very useful and used extensively in Android:
If necessary, you can assign a name to the anonymous object and store it in a variable. For example:

Companion objects
If you need a function or a property to be tied to a class rather than to instances of it (similar to static
methods in Java), you can declare it inside a companion object.

To create a companion object, you need to add companion keyword in front of the object declaration:

Now you can easily access any properties inside the companion object without creating an object of the
class:

Interfaces
Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations.
What makes them different from abstract classes is that interfaces cannot store state.

To declare an interface in Kotlin, use the interface keyword instead of class:


A class or object can implement one or more interfaces:

You can declare properties in interfaces. A property declared in an interface can either be abstract, or it
can provide implementations for accessors.

An interface can derive from other interfaces and thus both provide implementations for their members
and declare new functions and properties.
Collections in kotlin

A collection usually contains a number of objects of the same type. Objects in a collection are
called elements or items. For example, all the students in a department form a collection that can be
used to calculate their average age.

Collection types in Kotlin:

1. Array
2. List
3. Set
4. Map

Arrays
Arrays are very common in programming languages and kotlin is not an exception, each value in the
array is indexed by the position in the array.

The first value in the array has an index of zero, and the last value of the array has an index equals to the
array’s size minus one.

To create an array of any type, all you have to do is call arrayOf() method and pass your elements
separated by commas:

To print out the values of an array you have to iterate over them using forEach():
Another way you can iterate through the values is by using the Kotlin for loop:

You can get items from an array, and almost all the Kotlin collections, by using the square-brackets
syntax, within the brackets, you mention which index you are looking for:

To change a value at a certain index, you can use the same syntax, combined with the assignment
operator:

You can iterate over the array elements with their indexes using forEachIndexed() :
Lists
Lists are useful in programming. Since you will use lists in your everyday coding it is important to
understand them.

Lists are a dynamic version of arrays. In terms of memory, dynamic means that you can allocate each
element in any free memory slot.

List collection can be both mutable and immutable in terms of their size and contents.

Immutable Lists (read-only)


It’s very easily to create a list in kotlin, just use listOf() and pass your list elements between the braces:

But you can’t modify the list after it’s created because what we created above is not a mutable list.

Mutable Lists
To be able to add, remove and insert elements at certain indices, you have to create
a MutableList using mutableListOf().

Take the following snippet for example:

Because the list is now mutable, you can change items at indices, add items at specific indices and
remove items at provided indices.
Just like arrays you can use forEach() to iterate over the list elements:

Another useful method is map() which can be used to create a new list from existing list, here we are
squaring each element to create a new list:

Kotlin has rich set of very useful methods to work with lists, see the language documentation to find out
more.

Sets
A set is a collection of elements where each of the elements is unique and there are no duplicates.
They’re useful when you need to filter out duplicates. For example, you might use a set when storing ids
or users.

To create a set, use setOf() or mutableSetOf():


To remove an element it’s a little bit different from arrays or list because you need to pass the element
itself, of course you can only remove elements in a mutable Set:

Maps
Maps store pairs of objects where each value has a distinctive key. Each pair can be of any type you
want and contains two objects.

Maps are collections of key/value pairs. As such, maps are extremely useful when you are trying to tie
one value to a key like an id or a String identifier.

To create a map use mapOf() method and pass a key/value pairs separated by commas, In the initializer,
you use to() to create pairs of values with ease. Given that the pairs are of two strings, you are creating
a Map of types String, String:

Like with sets and lists, maps are immutable by default. To create a mutable map, you have to
use mutableMapOf():
Now, you can change its values by their keys:

Iterating through maps is a bit different from the rest of Kotlin collections. Since maps have two objects
for each element, you have to iterate over pairs, instead of single values. You can do this in the following
way:
Lambda expressions and Higher-Order functions

Lambda expressions

Lambda expressions, or simply lambdas, are essentially small chunks of code that can be passed to other
functions.

With lambdas, you can easily extract common code structures into library functions, and the Kotlin
standard library makes heavy use of them.

Instead of declaring a class and passing an instance of that class to a function, you can pass a function
directly.

You do not need to declare a function either: You can effectively, pass a block of code directly as a
function parameter.

This an example in Java for implementing a listener using anonymous inner classes: You need to create
an inner class every time.

The notation to express just the behavior—what should be done on clicking—helps eliminate redundant
code. In Kotlin, as in Java 8, you can use a lambda:

This Kotlin code does the same thing as an anonymous class in Java but is more concise and readable.
A lambda encodes a small piece of behavior that you can pass around as a value. It can be declared
independently and stored in a variable. But more frequently, it’s declared directly when passed to a
function.

Let’s create a lambda function that takes two Int parameters x and y, and it’s body consist of a single
expression that will sum the two numbers, a lambda expression is always surrounded by curly braces:

You can store a lambda expression in a variable and then treat this variable like a normal function (call it
with the corresponding arguments):

You have seen it before in the collections section, Kotlin use lambda expressions extensively with
collections.

For example kotlin forEach() use a lambda expression:

Higher-Order functions

A Higher-order function is a function that takes another function as an argument or returns one. Higher-
order functions can help you simplify your code, remove duplications and build a nice abstraction.
In Kotlin, functions can be represented as values using lambdas or function references. Therefore, a
higher-order function is any function to which you can pass a lambda or a function reference as an
argument, or a function which returns one, or both.

In order to declare a function that takes a lambda as an argument, you need to know how to declare the
type of the corresponding parameter.

You already saw how you could declare a lambda without declaring the type, relying on Kotlin’s type
inference:

But you can explicitly declare the type of the lambda, you put the function parameter types in
parentheses, followed by an arrow and the return type of the function:

Now let us create a simple higher-order function that takes a function called operation that has two Int
parameters and a return type of Int:

The function performs an arbitrary operation on two numbers, 2 and 3, and prints the result.

The syntax for calling the function passed as an argument is the same as calling a regular function: you
put the parentheses after the function name, and you put the parameters inside the parentheses.
Scope Functions

A scope function executes a block of code within the context of an object. Scope functions uses a
lambda expression.

Kotlin have five scope functions:

 let
 run
 with
 apply
 also

Basically, these functions do the same: execute a block of code on an object. What is different is how
this object becomes available inside the block and what is the result of the whole expression.

let
The context object is available as an argument (it). The return value is the lambda result.

let can be used to invoke one or more functions on results of call chains:

let is often used for executing a code block only with non-null values:
with
A non-extension function: the context object is passed as an argument, but inside the lambda, it's
available as a receiver (this). The return value is the lambda result.

We recommend with for calling functions on the context object without providing the lambda result. In
the code, with can be read as “with this object, do the following.”:

Another use case for with is introducing a helper object whose properties or functions will be used for
calculating a value:

Run
The context object is available as a receiver (this). The return value is the lambda result. run is useful
when your lambda contains both the object initialization and the computation of the return value.
apply
The context object is available as a receiver (this). The return value is the object itself.

Use apply for code blocks that don't return a value and mainly operate on the members of the receiver
object.

The common case for apply is the object configuration. Such calls can be read as “apply the following
assignments to the object.”:

also
The context object is available as an argument (it). The return value is the object itself.

also is good for performing some actions that take the context object as an argument. Use also for
actions that need a reference rather to the object than to its properties and functions, or when you
don't want to shadow this reference from an outer scope.

When you see also in the code, you can read it as “and also do the following with the object.”:
Final thoughts

Thank you for taking your valuable time to read this book, I hope you have found some value on its
pages.

Now you have the knowledge but you have to apply it somewhere, you have to practice to get better
each day.

One of the great uses of Kotlin is Android Development; if you are interested in Android Development
please follow me on My Instagram account:: @androidevelopment where I talk in-depth about Android
and Kotlin.

Alternatively, connect with me personally on My LinkedIn account

You might also like