CH 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Subject : Mobile Application Development in Android using Kotlin

Chapter - 1 : Introduction to Kotlin Programming

1) Basics of Kotlin, Operations and Priorities

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

iOS, tvOS, watchOS

Linux

Windows (MinGW)

Android NDK

Many more...

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Kotlin Program Entry Point

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() {

var string: String = "Hello, World!"

println("$string")

When you run the above Kotlin program, it will generate the following output:

Hello, World!

Entry Point with Parameters

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

Single line comments

// This is a comment

Multiline Comments

/* This is a multi-line comment and it can span

* as many lines as you like

*/

Kotlin Variable Types

fun main() {

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

var name: String = "Zara Ali"

var age: Int = 19

println("Name = $name")

println("Age = $age")

name = "Nuha Ali"

age = 11

println("Name = $name")

println("Age = $age")

}
Output

Name = Zara Ali


Age = 19
Name = Nuha Ali
Age = 11

Kotlin Variable Naming Rules

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.

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Data Types

Operators

(a) Kotlin Arithmetic Operators

(b) Kotlin Relational Operators

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

(c) Kotlin Assignment Operators

(d) Kotlin Unary Operators

(e) Kotlin Logical 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

The syntax of a traditional if...else expression is as follows:

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

if (condition) {

// code block A to be executed if condition is true

} else {

// code block B to be executed if condition is false

Example

fun main(args: Array<String>) {

val age:Int = 10

if (age > 18) {

print("Adult")

} else {

print("Minor")

Output

Minor

Kotlin if...else Expression

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

val result = if (condition) {

// code block A to be executed if condition is true

} else {

// code block B to be executed if condition is false

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Examples

fun main(args: Array<String>) {

val age:Int = 10

val result = if (age > 18) {

"Adult"

} else {

"Minor"

println(result)

output

Minor

Kotlin if...else...if Ladder

You can use else if condition to specify a new condition if the first condition is false.

Syntax

if (condition1) {

// code block A to be executed if condition1 is true

} else if (condition2) {

// code block B to be executed if condition2 is true

} else {

// code block C to be executed if condition1 and condition2 are false

Example

un main(args: Array<String>) {

val age:Int = 13

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

val result = if (age > 19) {

"Adult"

} else if ( age > 12 && age < 20 ){

"Teen"

} else {

"Minor"

print("The value of result : ")

println(result)

output

The value of result : Teen

Kotlin Nested if Expression

Kotlin allows to put an if expression inside another if expression. This is called nested if expression

Syntax

if(condition1) {

// code block A to be executed if condition1 is true

if( (condition2) {

// code block B to be executed if condition2 is true

}else{

// code block C to be executed if condition2 is fals

} else {

// code block D to be executed if condition1 is false

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

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

fun main(args: Array<String>) {

val day = 2

val result = when (day) {

1 -> "Monday"

2 -> "Tuesday"

3 -> "Wednesday"

4 -> "Thursday"

5 -> "Friday"

6 -> "Saturday"

7 -> "Sunday"

else -> "Invalid day."

println(result)

output

Tuesday

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Kotlin when as Statement

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

fun main(args: Array<String>) {

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")

else -> println("Invalid day.")

output

Tuesday

3) Loop Control, Data Structures(Collections)

Kotlin For Loop

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

for (item in collection) {

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

// body of loop

Example

fun main(args: Array<String>) {

for (item in 1..5) {

println(item)

output

Example

fun main(args: Array<String>) {

for (item in 5 downTo 1 step 2) {

println(item)

output

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

While Loop

Kotlin while loop executes its body continuously as long as the specified condition is true

Kotlin while loop is similar to Java while loop.

Syntax

while (condition) {

// body of the loop

Example

fun main(args: Array<String>) {

var i = 5;

while (i > 0) {

println(i)

i--

output

Kotlin do...while Loop

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{

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

// body of the loop

}while( condition )

Example

fun main(args: Array<String>) {

var i = 5;

do{

println(i)

i--

}while(i > 0)

output

Kotlin Break Statement

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

// Using break in for loop

for (...) {

if(test){

break

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

// Using break in while loop

while (condition) {

if(test){

break

// Using break in do...while loop

do {

if(test){

break

}while(condition)

Example

fun main(args: Array<String>) {

var i = 0;

while (i++ < 100) {

println(i)

if( i == 3 ){

break

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

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() {

val theList = listOf("one", "two", "three", "four")

println(theList)

Output

[one, two, three, four]

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Loop through Kotlin Lists

fun main() {

val theList = listOf("one", "two", "three", "four")

println(theList.toString())

output

[one, two, three, four]

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.

Creating Kotlin Sets

For set creation, use the standard library functions setOf() for read-only sets and mutableSetOf() for
mutable sets.

Example

fun main() {

val theSet = setOf("one", "two", "three", "four")

println(theSet)

output

[one, two, three, four]

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.

A Kotlin map can be either mutable (mutableMapOf) or read-only (mapOf).

Maps are also known as dictionaries or associative arrays in other programming languages.

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Creating Kotlin Maps

For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for
mutable maps.

Example

fun main() {

val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)

println(theMap)

output

{one=1, two=2, three=3, four=4}

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 Built-in Functions

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.

fun main(args: Array<String>) {

println("Hello, World!")

User-Defined Functions

Kotlin allows us to create our own function using the keyword fun.

fun functionName(){

// body of function

Example

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

fun main(args: Array<String>) {

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

fun main(args: Array<String>) {

val a = 10

val b = 20

printSum(a, b)

fun printSum(a:Int, b:Int){

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.

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Kotlin Recursive Function

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.

Kotlin Tail Recursion

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 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.

Kotlin Inline Function

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

class ClassName { // Class Header

//

// Variables or data members

// Member functions or Methods

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

//

...

...

Kotlin Objects

var varName = ClassName()

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

open class ABC {

fun think () {

println("Hey!! i am thiking ")

class BCD: ABC(){ // inheritence happend using default constructor

fun main(args: Array<String>) {

var a = BCD()

a.think()

output

Hey!! i am thiking

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

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.

abstract class Person {

var age: Int = 40

abstract fun setAge() // Abstract Method

fun getAge() { // Non-Abstract Method

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 {

var myVar: String // abstract property

fun absMethod() // abstract method

fun sayHello() = "Hello there" // method with default implementation

Super

The super keyword will call the constructor of the super or parent class to initialize the properties of the
parent class.

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

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.

There are four visibility modifiers in Kotlin:

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.

Prepared By : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

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

internal class InternalExample {

class publicExample{

internal val i = 1

internal fun doSomething() {

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.

Prepared By : Shivani Trivedi

You might also like