CH 1
CH 1
CH 1
Kotlin is a programming language introduced by JetBrains in 2011, the official designer of the most
intelligent Java IDE, named Intellij IDEA. This is a strongly statically typed general-purpose
programming language that runs on JVM. In 2017, Google announced Kotlin is an official language for
android development. Kotlin is an open source programming language that combines object-oriented
programming and functional features into a unique platform. The content is divided into various chapters
that contain related topics with simple and useful examples.
Kotlin is a programming language and has its own architecture to allocate memory and produce a quality
output to the end user.
Following are the different scenarios where Kotlin compiler will work differently.
Compile Kotlin into bytecode which can run on JVM. This bytecode is exactly equal to the byte
code generated by the Java .class file.
Whenever Kotlin targets JavaScript, the Kotlin compiler converts the .kt file into ES5.1 and
generates a compatible code for JavaScript.
Kotlin compiler is capable of creating platform basis compatible codes via LLVM.
Kotlin Multiplatform Mobile (KMM) is used to create multiplatform mobile applications with
code shared between Android and iOS.
Whenever two byte coded files ( Two different programs from Kotlin and Java) runs on the JVM, they
can communicate with each other and this is how an interoperable feature is established in Kotlin for
Java.
Kotlin Native
Kotlin/Native is a technology for compiling Kotlin code to native binaries, which can run without a
virtual machine. Kotlin/Native supports the following platforms:
macOS
Linux
Windows (MinGW)
Android NDK
Many more...
An entry point of a Kotlin application is the main() function. A function can be defined as a block of code
designed to perform a particular task.
Let's start with a basic Kotlin program to print "Hello, World!" on the standard output:
fun main() {
println("$string")
When you run the above Kotlin program, it will generate the following output:
Hello, World!
Another form of main() function accepts a variable number of String arguments as follows:
fun main(args: Array<String>){
println("Hello, world!")
}
When you run the above Kotlin program, it will generate the following output:
Hello, World!
Comments
// This is a comment
Multiline Comments
*/
fun main() {
println("Name = $name")
println("Age = $age")
age = 11
println("Name = $name")
println("Age = $age")
}
Output
There are certain rules to be followed while naming the Kotlin variables:
Kotlin variable names can contain letters, digits, underscores, and dollar signs.
Kotlin variable names should start with a letter, $ or underscores
Kotlin variables are case sensitive which means Zara and ZARA are two different variables.
Kotlin variable can not have any white space or other control characters.
Kotlin variable can not have names like var, val, String, Int because they are reserved keywords
in Kotlin.
Data Types
Operators
2) Decision Making
Kotlin if...else expressions works like an if...else expression in any other Modern Computer
Programming. So let's start with our traditional if...else statement available in Kotlin.
Syntax
if (condition) {
} else {
Example
val age:Int = 10
print("Adult")
} else {
print("Minor")
Output
Minor
Kotlin if...else can also be used as an expression which returns a value and this value can be assigned to a
variable. Below is a simple syntax of Kotlin if...else expression:
Syntax
} else {
Examples
val age:Int = 10
"Adult"
} else {
"Minor"
println(result)
output
Minor
You can use else if condition to specify a new condition if the first condition is false.
Syntax
if (condition1) {
} else if (condition2) {
} else {
Example
un main(args: Array<String>) {
val age:Int = 13
"Adult"
"Teen"
} else {
"Minor"
println(result)
output
Kotlin allows to put an if expression inside another if expression. This is called nested if expression
Syntax
if(condition1) {
if( (condition2) {
}else{
} else {
When Expression
Kotlin when expression is similar to the switch statement in C, C++ and Java.
Consider a situation when you have large number of conditions to check. Though you can use if..else if
expression to handle the situation, but Kotlin provides when expression to handle the situation in nicer
way. Using when expression is far easy and more clean in comparison to writing many if...else if
expressions. Kotlin when expression evaluates a section of code among many alternatives as explained in
below example.
Example
val day = 2
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
println(result)
output
Tuesday
Kotlin when can be used either as an expression or as a statement, simply like a switch statement in Java.
If it is used as an expression, the value of the first matching branch becomes the value of the overall
expression.
Example
val day = 2
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
output
Tuesday
Kotlin for loop iterates through anything that provides an iterator ie. that contains a countable number of
values, for example arrays, ranges, maps or any other collection available in Kotlin. Kotlin for loop is
equivalent to the foreach loop in languages like C#.
Syntax
// body of loop
Example
println(item)
output
Example
println(item)
output
While Loop
Kotlin while loop executes its body continuously as long as the specified condition is true
Syntax
while (condition) {
Example
var i = 5;
while (i > 0) {
println(i)
i--
output
The do..while is similar to the while loop with a difference that the this loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do{
}while( condition )
Example
var i = 5;
do{
println(i)
i--
}while(i > 0)
output
Kotlin break statement is used to come out of a loop once a certain condition is met. This loop could be a
for, while or do...while loop.
Syntax
for (...) {
if(test){
break
while (condition) {
if(test){
break
do {
if(test){
break
}while(condition)
Example
var i = 0;
println(i)
if( i == 3 ){
break
output
Collections
Collections are a common concept for most programming languages. A collection usually contains a
number of objects of the same type and Objects in a collection are called elements or items.
The Kotlin Standard Library provides a comprehensive set of tools for managing collections. The
following collection types are relevant for Kotlin:
Kotlin List - List is an ordered collection with access to elements by indices. Elements can occur more
than once in a list.
Kotlin Set - Set is a collection of unique elements which means a group of objects without repetitions.
Kotlin Map - Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to
exactly one value.
List
Kotlin list is an ordered collection of items. A Kotlin list can be either mutable (mutableListOf) or read-
only (listOf). The elements of list can be accessed using indices. Kotlin mutable or immutable lists can
have duplicate elements.
Example
fun main() {
println(theList)
Output
fun main() {
println(theList.toString())
output
Set
Kotlin set is an unordered collection of items. A Kotlin set can be either mutable (mutableSetOf) or read-
only (setOf). Kotlin mutable or immutable sets do not allow to have duplicate elements.
For set creation, use the standard library functions setOf() for read-only sets and mutableSetOf() for
mutable sets.
Example
fun main() {
println(theSet)
output
Map
Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with
one value. The same value can be associated with multiple keys though. We can declare the keys and
values to be any type; there are no restrictions.
Maps are also known as dictionaries or associative arrays in other programming languages.
For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for
mutable maps.
Example
fun main() {
println(theMap)
output
4) Functions
A function is a block of code which is written to perform a particular task. Functions are supported by all
the modern programming languages and they are also known as methods or subroutines.
Kotlin provides a number of built-in functions, we have used a number of buil-in functions in our
examples. For example print() and println() are the most commonly used built-in function which we use
to print an output to the screen.
println("Hello, World!")
User-Defined Functions
Kotlin allows us to create our own function using the keyword fun.
fun functionName(){
// body of function
Example
printHello()
fun printHello(){
println("Hello, World!")
Function Parameters
A user-defined function can take zero or more parameters. Parameters are options and can be used based
on requirement. For example, our above defined function did not make use of any paramenter.
Example
val a = 10
val b = 20
printSum(a, b)
println(a + b)
When you run the above Kotlin program, it will generate the following output:
30
Unit-returning Functions
If a function does not return a useful value, its return type is Unit. Unit is a type with only one value
which is Unit.
Recursion functions are useful in many scenerios like calculating factorial of a number or generating
fibonacci series. Kotlin supports recursion which means a Kotlin function can call itself.
A recursive function is eligible for tail recursion if the function call to itself is the last operation it
performs.
Higher-Order Functions
A higher-order function is a function that takes another function as parameter and/or returns a function.
Kotlin lambda is a function which has no name and defined with a curly braces {} which takes zero or
more parameters and body of function.
The body of function is written after variable (if any) followed by -> operator.
An inline function is declared with inline keyword. The use of inline function enhances the performance
of higher order function. The inline function tells the compiler to copy parameters and functions to the
call site.
5) Object Oriented Programming: Inheritance abstract, interface, super and this, visibility
modifiers.
Kotlin Classes
Syntax
//
//
...
...
Kotlin Objects
Inheritance
Inheritance can be defined as the process where one class acquires the members (methods and properties)
of another class. With the use of inheritance the information is made manageable in a hierarchical order.
A class which inherits the members of other class is known as subclass (derived class or child class) and
the class whose members are being inherited is known as superclass (base class or parent class).
Example
fun think () {
var a = BCD()
a.think()
output
Hey!! i am thiking
abstract
A Kotlin abstract class is similar to Java abstract class which can not be instantiated. This means we
cannot create objects of an abstract class. However, we can inherit subclasses from a Kotlin abstract class.
A Kotlin abstract class is declared using the abstract keyword in front of class name. The properties and
methods of an abstract class are non-abstract unless we explictly use abstract keyword to make them
abstract. If we want to override these members in the child class then we just need to use override
keyword infront of them in the child class.
return age
Interface
Kotlin, the interface works exactly similar to Java 8, which means they can contain method
implementation as well as abstract methods declaration. An interface can be implemented by a class in
order to use its defined functionality. We have already introduced an example with an interface in Chapter
6 - section “anonymous inner class”. In this chapter, we will learn more about it. The keyword “interface”
is used to define an interface in Kotlin as shown in the following piece of code.
interface ExampleInterface {
Super
The super keyword will call the constructor of the super or parent class to initialize the properties of the
parent class.
This
In Kotlin, the “this” keyword allows us to refer to the instance of a class whose function we happen to be
running.
Visibility Modifiers
The Kotlin visibility modifiers are the keywords that set the visibility of classes, objects, interface,
constructors, functions as well as properties and their setters. Though getters always have the same
visibility as their properties, so we can not set their visibility.
public
private
protected
internal
Public Modifier
Public modifier is accessible from anywhere in the project workspace. If no access modifier is specified,
then by default it will be in the public scope. In all our previous examples, we have not mentioned any
modifier, hence, all of them are in the public scope. Following is an example to understand more on how
to declare a public variable or method.
Private Modifier
The classes, methods, packages and other properties can be declared with a private modifier. This
modifier has almost the exact opposite meaning of public which means a private member can not be
accessed outside of its scope. Once anything is declared as private, then it can be accessible within its
immediate scope only. For instance, a private package can be accessible within that specific file. A
private class or interface can be accessible only by its data members, etc.
Protected Modifier
Protected is another access modifier for Kotlin, which is currently not available for top level declaration
like any package cannot be protected. A protected class or interface or properties or function is visible to
the class itself and it's subclasses only.
Internal Modifier
Internal is a newly added modifier in Kotlin. If anything is marked as internal, then the specific field will
marked as the internal field. An Internal package is visible only inside the module under which it is
implemented. An internal class interface is visible only by other class present inside the same package or
the module. In the following example, we will see how to implement an internal method.
package one
class publicExample{
internal val i = 1
In the above example, class InternalExample is only accessible from inside the same module, similarly
variable i and function doSomething() are also accessible from inside the same module only, even though
the class publicExample can be accessed from anywhere because this class has public visibility by
default.