0% found this document useful (0 votes)
28 views26 pages

501 02 CH 1

The document provides an overview of Kotlin, a statically typed programming language developed by JetBrains, highlighting its features, advantages, and applications, particularly in Android development. It covers essential concepts such as variable types, data classes, and the use of IntelliJ IDE for Kotlin programming. Additionally, it explains Kotlin's syntax, data types, and standard input/output operations.

Uploaded by

cd217251
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)
28 views26 pages

501 02 CH 1

The document provides an overview of Kotlin, a statically typed programming language developed by JetBrains, highlighting its features, advantages, and applications, particularly in Android development. It covers essential concepts such as variable types, data classes, and the use of IntelliJ IDE for Kotlin programming. Additionally, it explains Kotlin's syntax, data types, and standard input/output operations.

Uploaded by

cd217251
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/ 26

A.Y.

- 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing

Unit-1: Introduction to Kotlin


1.1 Concepts of Kotlin and its introduction.
1.2 Downloading IntelliJ and its settings.
1.3 Variables:
1.3.1 val vs. var, Byte, Short, Int, Long, Float, Double, Boolean, and Char.
1.3.2 String, Nullable variables.
1.4 Conditional statements: if and when. Difference between if and when.
1.4.1 ranges, types, values of function calls
1.5 Arrays and Lists:
1.5.1 create, modify, and access arrays
1.5.2 creating, modifying, and accessing lists
1.6 Loops (Iterative statements)
1.6.1 for and while loop.
1.6.2 break, continue and return

1.1 Concepts of Kotlin and its introduction.


 Kotlin is a statically typed, general-purpose programming language developed by
JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It
was first introduced by JetBrains in 2011 and a new language for the JVM.
 Kotlin is object-oriented language, and a “better language” than Java, but still be fully
interoperable with Java code.
 Kotlin is sponsored by Google, announced as one of the official languages for Android
Development in 2017.
Example of Kotlin –
fun main()
{
println("Hello Geeks");
}

Key Features of Kotlin:


1. Statically typed– Statically typed is a programming language characteristic that means
the type of every variable and expression is known at compile time. Although it is
statically typed language, it does not require you to explicitly specify the type of every
variable you declare.
[Statically typed languages
Perform type checking at compile time, before the code is executed. This means that if a
script contains errors, it won't compile until the errors are fixed. Statically typed languages,
like Java, C++, and C#, produce more reliable code because the compiler catches type-
related errors before the program runs. However, this approach is less flexible and produces
more optimized code.
Dynamically typed languages
Perform type checking at runtime, while the code is being executed. This means that scripts
can compile even if they contain errors, but this can lead to issues at runtime, such as
unexpected type errors or behavior. Dynamically typed languages, like Python, Ruby, and
JavaScript, offer more flexibility but produce less optimized code.]
2. Data Classes– In Kotlin, there are Data Classes which lead to auto-generation of
boilerplate like equals, hashCode, toString, getters/setters and much more.
In Kotlin only one line used to define the above class –
/* Kotlin Code */

PROF. BHUMIKA PATEL 1


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
data class Book(var title:String, var author:Author)
3. Concise – It drastically reduces the extra code written in other object-oriented
programming languages.
4. Safe – It provides the safety from most annoying and irritating NullPointerExceptions by
supporting nullability as part of its system.
Every variable in Kotlin is non-null by default.
String s = "Hello Geeks" // Non-null
If we try to assign s null value then it gives compile time error. So,

s = null // compile time error


To assign null value to any string string it should be declared as nullable.
String nullableStr? = null // compiles successfully
length() function also disabled on the nullable strings.
5. Interoperable with Java – Kotlin runs on Java Virtual Machine (JVM) so it is totally
interoperable with java. We can easily access use java code from kotlin and kotlin code
from java.
6. Functional and Object Oriented Capabilities – Kotlin has rich set of many useful
methods which includes higher-order functions, lambda expressions, operator
overloading, lazy evaluation, operator overloading and much more. Higher order
function is a function which accepts function as a parameter or returns a function or can
do both.
7. Smart Cast – It explicitly typecasts the immutable values and inserts the value in its
safe cast automatically.
If we try to access a nullable type of String (String? = “BYE”) without safe cast it will
generate a compile error.
fun main(args: Array){
var string: String? = "BYE"
print(string.length) // compile time error
}
}

fun main(args: Array){


var string: String? = "BYE"
if(string != null) { // smart cast
print(string.length)
}
}
8. Compilation time – It has higher performance and fast compilation time.
9. Tool- Friendly – It has excellent tooling support. Any of the Java IDEs – IntelliJ IDEA,
Eclipse and Android Studio can be used for Kotlin. We can also be run Kotlin program
from command line.

PROF. BHUMIKA PATEL 2


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
Advantages of Kotlin language:
 Easy to learn – Basic is almost similar to java.If anybody worked in java then easily
understand in no time.
 Kotlin is multi-platform – Kotlin is supported by all IDEs of java so you can write your
program and execute them on any machine which supports JVM.
 It‟s much safer than Java.
 It allows using the Java frameworks and libraries in your new Kotlin projects by using
advanced frameworks without any need to change the whole project in Java.
 Kotlin programming language, including the compiler, libraries and all the tooling is
completely free and open source and available on github. Here is the link for Github
https://github.com/JetBrains/kotlin

Applications of Kotlin language:


 You can use Kotlin to build Android Application.
 Kotlin can also compile to JavaScript, and making it available for the frontend.
 It is also designed to work well for web development and server-side development.

1.2 Downloading IntelliJ and its settings.


Kotlin IDE
The easiest way to get started with Kotlin, is to use an IDE.

An IDE (Integrated Development Environment) is used to edit and compile code.

In this chapter, we will use IntelliJ (developed by the same people that created Kotlin)
which is free to download from https://www.jetbrains.com/idea/download/.

Kotlin Install
Once IntelliJ is downloaded and installed, click on the New Project button to get started with
IntelliJ:

PROF. BHUMIKA PATEL 3


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing

Then click on "Kotlin" in the left side menu, and enter a name for your project:

PROF. BHUMIKA PATEL 4


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
Next, we need to install something called JDK (Java Development Kit) to get our Kotlin
project up and going. Click on the "Project JDK" menu, select "Download JDK" and select a
version and vendor (e.g. AdoptOpenJDK 11) and click on the "Download" button:

When the JDK is downloaded and installed, choose it from the select menu and then click on
the "Next" button and at last "Finish":

Now we can start working with our Kotlin project. Do not worry about all of the different buttons and functions in
IntelliJ. For now, just open the src (source) folder, and follow the same steps as in the image below, to create a
kotlin file:

PROF. BHUMIKA PATEL 5


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing

Select the "File" option and add a name to your Kotlin file, for example "Main":

Next, IntelliJ will build your project, and run the Kotlin file. The output will look something like this:

PROF. BHUMIKA PATEL 6


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing

Kotlin Syntax
In the previous chapter, we created a Kotlin file called Main.kt, and we used the following
code to print "Hello World" to the screen:
fun main()
{
println("Hello World")
}

 The fun keyword is used to declare a function. A function is a block of code designed to
perform a particular task. In the example above, it declares the main() function.
 The main() function is something you will see in every Kotlin program. This function is
used to execute code. Any code inside the main() function's curly brackets {} will be
executed.
 For example, the println() function is inside the main() function, meaning that this will
be executed. The println() function is used to output/print text, and in our example it
will output "Hello World".

Good To Know: In Kotlin, code statements do not have to end with a semicolon (;) (which is
often required for other programming languages, such as Java, C++, C#, etc.).

Main Parameters
Before Kotlin version 1.3, it was required to use the main() function with parameters, like:
fun main(args : Array<String>). The example above had to be written like this to work:

fun main(args : Array<String>) {


println("Hello World")
}

PROF. BHUMIKA PATEL 7


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
Kotlin Comments
Comments can be used to explain Kotlin code, and to make it more readable. It can also be
used to prevent execution when testing alternative code.

 Single-line Comments
Single-line comments starts with two forward slashes (//).
Any text between // and the end of the line is ignored by Kotlin (will not be executed).
This example uses a single-line comment before a line of code:
// This is a comment
println("Hello World")

 Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Kotlin.
This example uses a multi-line comment (a comment block) to explain the code:
/* The code below will print the words Hello World
to the screen, and it is amazing */
println("Hello World")

1.3 Variables:
1.3.1 val vs. var, Byte, Short, Int, Long, Float, Double, Boolean, and Char.
1.3.2 String, Nullable variables

In Kotlin, every variable should be declared before it‟s used. Without declaring a variable,
an attempt to use the variable gives a syntax error. Declaration of the variable type also
decides the kind of data you are allowed to store in the memory location. In case of local
variables, the type of variable can be inferred from the initialized value.
var rollno = 55
var name = "Praveen"
println(rollno)
println(name)

Above we have the local variable rollno whose value is 55 and it‟s type is Integer because
the literal type is Int and another variable is name whose type is String. In Kotlin, variables
are declared using two types –
 Immutable using val keyword
 Mutable using var keyword

1. Immutable Variables –
Immutable is also called read-only variables. Hence, we cannot change the value of the
variable declared using val keyword.
val myName = "Gaurav"
myName = "Praveen" // compile time error

// It gives error Kotlin Val cannot be reassigned

Note: Immutable variable is not a constant because it can be initialized with the value of a
variable. It means the value of immutable variable doesn’t need to be known at compile-
time, and if it is declared inside a construct that is called repeatedly, it can take on a
different value on each function call.
var myBirthDate = "02/12/1993"

PROF. BHUMIKA PATEL 8


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
val myNewBirthDate = myBirthDate
println(myNewBirthDate)

2. Mutable Variables –
In Mutable variable we can change the value of the variable.
var myAge = 25
myAge = 26 // compiles successfully
println("My new Age is ${myAge}")

Output:
My new Age is 26

Scope of a variable – A variable exists only inside the block of code( {………….} ) where it
has been declared. You cannot access the variable outside the loop. Same variable can be
declared inside the nested loop – so if a function contains an argument x and we declare a
new variable x inside the same loop, then x inside the loop is different than the argument.
Naming Convention – Every variable should be named using lowerCamelCase.
val myBirthDate = "02/12/1994"

Kotlin Data Types


In Kotlin, the type of a variable is decided by its value:
Sometimes you have to specify the type, and often you don't. Anyhow, it is good to know
what the different types represent. Data types are divided into different groups:
 Numbers
 Characters
 Booleans
 Strings
 Arrays
Numbers
Number types are divided into two groups:
Integer types store whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are Byte, Short, Int and Long.
Floating point types represent numbers with a fractional part, containing one or more
decimals. There are two types: Float and Double.
If you don't specify the type for a numeric variable, it is most often returned as Int for
whole numbers and Double for floating point numbers.

Integer Types
Byte
The Byte data type can store whole numbers from -128 to 127. This can be used instead of
Int or other integer types to save memory when you are certain that the value will be within
-128 and 127:
Short
The Short data type can store whole numbers from -32768 to 32767:
Int
The Int data type can store whole numbers from -2147483648 to 2147483647:

PROF. BHUMIKA PATEL 9


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing

Long
The Long data type can store whole numbers from -9223372036854775807 to
9223372036854775807. This is used when Int is not large enough to store the value.
Optionally, you can end the value with an "L":
Difference Between Int and Long
A whole number is an Int as long as it is up to 2147483647. If it goes beyond that, it is
defined as Long:

Floating Point Types


Floating point types represent numbers with a decimal, such as 9.99 or 3.14515.
The Float and Double data types can store fractional numbers:
fun main() {
val myNum: Float = 5.75F
println(myNum)
}

fun main() {
val myNum: Double = 19.99
println(myNum)
}
Strings
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
fun main() {
val myText: String = "Hello World"
println(myText)
}

Example of Data Type


fun main() {
val myNum: Int = 5 // Int
val myDoubleNum: Double = 5.99 // Double
val myLetter: Char = 'D' // Char
val myBoolean: Boolean = true // Boolean
val myText: String = "Hello" // String
println(myNum)
println(myDoubleNum)
println(myLetter)
println(myBoolean)
println(myText)
}

PROF. BHUMIKA PATEL 10


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing

Kotlin Standard Input/Output


Kotlin Output –
Kotlin standard output is the basic operation performed to flow byte streams from main
memory to the output device. You can output any of the data types integer, float and any
patterns or strings on the screen of the system.
You can use any one of the following function to display output on the screen.
 print() function
 println() function
Here is the Kotlin program for standard output.
fun main(args: Array<String>)
{
print("Hello, Geeks! ")
println("This is Kotlin tutorial.")
}
Output:
Hello, Geeks! This is Kotlin tutorial.

Difference between println() and print() –


print() function prints the message inside the double quotes.
println() function prints the message inside the double quotes and moves to the beginning
of the next line.
kotlin program to print string:
fun main(args: Array<String>)
{
println("GeeksforGeeks")
println("A Computer Science portal for Geeks")

print("GeeksforGeeks - ")
print("A Computer Science portal for Geeks")
}
Output:
GeeksforGeeks
A Computer Science portal for Geeks
GeeksforGeeks - A Computer Science portal for Geeks

Print literals and Variables –


fun sum(a: Int,b: Int) : Int{
return a + b
}
fun main(args: Array<String>){

var a = 10
var b = 20
var c = 30L
var marks = 40.4

println("Sum of {$a} and {$b} is : ${sum(a,b)}")

PROF. BHUMIKA PATEL 11


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
println("Long value is: $c")
println("marks")
println("$marks")
}
Output:
Sum of {10} and {20} is: 30
Long value is: 30
marks
40.4

Kotlin Input –
Kotlin standard input is the basic operation performed to flow byte streams from input
device such as Keyboard to the main memory of the system.
You can take input from user with the help of the following function:
 readline() method
 Scanner class
Take input from user using readline() method –
fun main(args : Array<String>) {
print("Enter text: ")
var input = readLine()
print("You entered: $input")
}

Kotlin Type Conversion


Type conversion (also called as Type casting) refers to changing the entity of one data type
variable into another data type. As we know Java supports implicit type conversion from
smaller to larger data types. An integer value can be assigned to the long data type.
Example:
var myNumber = 100
var myLongNumber: Long = myNumber.toLong() // compiles successfully

The following helper function can be used to convert one data type into another:
 toByte()
 toShort()
 toInt()
 toLong()
 toFLoat()
 toDouble()
 toChar()

Conversion from larger to smaller data type


var myLongNumber = 10L
var myNumber2: Int = myLongNumber1.toInt()

Kotlin Program to convert the one data type into another:


fun main(args: Array<String>)
{

println("259 to byte: " + (259.toByte()))

PROF. BHUMIKA PATEL 12


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
println("50000 to short: " + (50000.toShort()))
println("21474847499 to Int: " + (21474847499.toInt()))
println("10L to Int: " + (10L.toInt()))
println("22.54 to Int: " + (22.54.toInt()))
println("22 to float: " + (22.toFloat()))
println("65 to char: " + (65.toChar()))
// Char to Number is deprecated in kotlin
println("A to Int: " + ('A'.toInt()))
}
OUTPUT:
259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
10L to Int: 10
22.54 to Int: 22
22 to float: 22.0
65 to char: A
A to Int: 65

1.4 Conditional statements: if and when. Difference between if and when.


1.4.1 ranges, types, values of function calls
Kotlin if-else expression
Decision making in programming is similar to decision-making in real life. In programming
too, a certain block of code needs to be executed when some condition is fulfilled. A
programming language uses control statements to control the flow of execution of a
program based on certain conditions. If the condition is true then it enters into the
conditional block and executes the instructions.
There are different types of if-else expressions in Kotlin:
 if expression
 if-else expression
 if-else-if ladder expression
 nested if expression
if statement:
It is used to specify whether a block of statements will be executed or not, i.e. if a condition
is true, then only the statement or block of statements will be executed otherwise it fails to
execute.
Syntax:
if(condition)
{

// code to run if condition is true


}

if-else statement:
if-else statement contains two blocks of statements. „if‟ statement is used to execute the
block of code when the condition becomes true and „else‟ statement is used to execute a
block of code when the condition becomes false.
Syntax:
if(condition) {
// code to run if condition is true

PROF. BHUMIKA PATEL 13


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
}
else {
// code to run if condition is false
}
if-else-if ladder expression:
Here, a user can put multiple conditions. All the „if‟ statements are executed from the top to
bottom. One by one all the conditions are checked and if any of the conditions is found to be
true then the code associated with the if statement will be executed and all other
statements bypassed to the end of the block. If none of the conditions is true, then by
default the final else statement will be executed.
Syntax:
if(Firstcondition) {
// code to run if condition is true
}
else if(Secondcondition) {
// code to run if condition is true
}
else{
}

Below is the Kotlin program to determine whether the number is positive,


negative, or equal to zero.
import java.util.Scanner

fun main(args: Array<String>) {

// create an object for scanner class


val reader = Scanner(System.in)
print("Enter three numbers: ")

var num1 = reader.nextInt()


var num2 = reader.nextInt()
var num3 = reader.nextInt()

var max = if ( num1 > num2) {


if (num1 > num3) {
"$num1 is the largest number"
}
else {
"$num3 is the largest number"
}
}
else if( num2 > num3){
"$num2 is the largest number"
}
else{
"$num3 is the largest number"
}
println(max)

}
OUTPUT:

PROF. BHUMIKA PATEL 14


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
Enter three numbers: 12
45
77
77 is the largest number

Kotlin when expression


In Kotlin, when replaces the switch operator of other languages like Java. A certain block of
code needs to be executed when some condition is fulfilled. The argument of when
expression compares with all the branches one by one until some match is found. After the
first match is found, it reaches to end of the when block and executes the code next to the
when block. Unlike switch cases in java or any other programming language, we do not
require a break statement at the end of each case. In Kotlin, when can be used in two
ways:
 when as a statement
 when as an expression

Using when as a statement with else


when can be used as a statement with or without else branch. If it is used as a statement,
the values of all individual branches are compared sequentially with the argument and
execute the corresponding branch where the condition matches. If none of the branches is
satisfied with the condition then it will execute the else branch.
fun main (args : Array<String>) {
print("Enter the name of heavenly body: ")
var name= readLine()!!.toString()
when(name)
{
"Sun" -> print("Sun is a Star")
"Moon" -> print("Moon is a Satellite")
"Earth" -> print("Earth is a planet")
else -> print("I don't know anything about it")
}
}

Output:
Enter the name of heavenly body: Sun
Sun is a Star
Enter the name of heavenly body: Mars
I don't know anything about it

Using when as an expression


If it is used as an expression, the value of the branch with which condition satisfied will be
the value of overall expression. As an expression when returns a value with which the
argument matches and we can store it in a variable or print directly.
fun main(args : Array<String>) {
print("Enter number of the Month: ")
var monthOfYear = readLine()!!.toInt()
var month= when(monthOfYear) {
1->"January"
2->"February"
3->"March"
4->"April"

PROF. BHUMIKA PATEL 15


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
5->"May"
6->"June"
7->"July"
8->"August"
9->"September"
10->"October"
11->"November"
12->"December"
else-> "Not a month of year"
}
print(month)
}
Output:
Enter number of the Month: 8
August

If none of the branch conditions are satisfied with the argument, the else branch is
executed. As an expression, the else branch is mandatory, unless the compiler can prove
that all possible cases are covered with branch conditions. If we cannot use else branch it
will give a compiler error.
Error:(6, 17) Kotlin: 'when' expression must be exhaustive, add necessary 'else' branch

1.5 Arrays and Lists:


1.5.1 create, modify, and access arrays
Array is one of the most fundamental data structure in practically all programming
languages. The idea behind an array is to store multiple items of the same data-type, such
as an integer or string under a single variable name.
Arrays are used to organize data in programming so that a related set of values can be
easily sorted or searched.
Here are some basic properties of arrays –
 They are stored in contiguous memory locations.
 They can be accessed programmatically through their indexes (array[1], array[0], etc.)
 They are mutable.
 Their size is fixed.

Creating an array –
In Kotlin, arrays are not a native data type, but a mutable collection of similar items which
are represented by the Array class.
There are two ways to define an array in Kotlin.
1. Using the arrayOf() function
2. Using the Array constructor

1. Using the arrayOf() function –


We can use the library function arrayOf() to create an array by passing the values of the
elements to the function.
Syntax:
val num = arrayOf(1, 2, 3, 4) //implicit type declaration
val num = arrayOf<Int>(1, 2, 3) //explicit type declaration

PROF. BHUMIKA PATEL 16


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
Kotlin program of creating array using arrayOf() and arrayOf<Int> functions-
fun main()
{
val arrayname1 = arrayOf(1, 2, 3, 4, 5) // declaring an array using arrayOf()

for (i in 0..arrayname1.size-1)
{
print(" "+arrayname1[i])
}
println() // declaring an array using arrayOf<Int>
val arrayname2 = arrayOf<Int>(10, 20, 30, 40, 50)

for (i in 0..arrayname2.size-1)
{
print(" "+ arrayname2[i])
}
}
OUTPUT:
1 2 3 4 5
10 20 30 40 50

2. Using the Array constructor –


Since Array is a class in Kotlin, we can also use the Array constructor to create an array.
The constructor takes two parameters:
1. The size of the array
2. A function which accepts the index of a given element and returns the initial value of
that element.
Syntax:
val num = Array(3, {i-> i*1})

In the above example, we pass the size of the array as 3 and a lambda expression which
initializes the element values from 0 to 9.

1.5.2 Creating, modifying, and accessing lists


Kotlin – Lists : 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.
Creating Kotlin Lists: For list creation, use the standard library functions listOf() for read-
only lists and mutableListOf() for mutable lists.
To prevent unwanted modifications, obtain read-only views of mutable lists by casting them
to List.
fun main() {
val theList = listOf("one", "two", "three", "four")
println(theList)

val theMutableList = mutableListOf("one", "two", "three", "four")


println(theMutableList)
}

PROF. BHUMIKA PATEL 17


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
OUTPUT:
[one, two, three, four]
[one, two, three, four]

Loop through Kotlin Lists


There are various ways to loop through a Kotlin list. Lets study them one by one:
Using toString() function
fun main() {
val theList = listOf("one", "two", "three", "four")
println(theList.toString())
}
OUTPUT:
[one, two, three, four]
Using Iterator
fun main() {
val theList = listOf("one", "two", "three", "four")

val itr = theList.listIterator()


while (itr.hasNext()) {
println(itr.next())
}
}
Using for loop
fun main() {
val theList = listOf("one", "two", "three", "four")

for (i in theList.indices) {
println(theList[i])
}
}
Using forEach
fun main() {
val theList = listOf("one", "two", "three", "four")

theList.forEach { println(it) }
}
Size of Kotlin List
We can use size property to get the total number of elements in a list:
fun main() {
val theList = listOf("one", "two", null, "four", "five")

println("Size of the list " + theList.size)


}
Output:
Size of the list 5
The "in" Operator
The in operator can be used to check the existence of an element in a list.
Example:
fun main() {
val theList = listOf("one", "two", "three", "four")

PROF. BHUMIKA PATEL 18


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
if("two" in theList){
println(true)
}else{
println(false)
}
}

The contain() Method


The contain() method can also be used to check the existence of an element in a list.
Example:
fun main()
{
val theList = listOf("one", "two", "three", "four")
if(theList.contains("two"))
{
println(true)
} else{
println(false)
}
}
OUTPUT:
true

The isEmpty() Method


The isEmpty() method returns true if the collection is empty (contains no elements), false
otherwise. Example
fun main() {
val theList = listOf("one", "two", "three", "four")

if(theList.isEmpty()){
println(true)
}else{
println(false)
}
}
OUTPUT:
false

The indexOf() Method


The indexOf() method returns the index of the first occurrence of the specified element in
the list, or -1 if the specified element is not contained in the list.
Example:
fun main() {
val theList = listOf("one", "two", "three", "four")

println("Index of 'two' : " + theList.indexOf("two"))


}
OUTPUT:
Index of 'two' : 1

The get() Method

PROF. BHUMIKA PATEL 19


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
The get() method can be used to get the element at the specified index in the list. First
element index will be zero.

Example
fun main() {
val theList = listOf("one", "two", "three", "four")

println("Element at 3rd position " + theList.get(2))


}
OUTPUT:
Element at 3rd position three

List Addition
We can use + operator to add two or more lists into a single list. This will add second list
into first list, even duplicate elements will also be added.
Example
fun main() {
val firstList = listOf("one", "two", "three")
val secondList = listOf("four", "five", "six")
val resultList = firstList + secondList

println(resultList)
}
OUTPUT:
[one, two, three, four, five, six]

List Subtraction
We can use - operator to subtract a list from another list. This operation will remove the
common elements from the first list and will return the result.
fun main() {
val firstList = listOf("one", "two", "three")
val secondList = listOf("one", "five", "six")
val resultList = firstList - secondList

println(resultList)
}
OUTPUT:
[two, three]
Slicing a List
We can obtain a sublist from a given list using slice() method which makes use of range of
the elements indices.
Example:
fun main() {
val theList = listOf("one", "two", "three", "four", "five")
val resultList = theList.slice( 2..4)

println(resultList)
}
OUTPUT:
[three, four, five]

PROF. BHUMIKA PATEL 20


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
Removing null a List
We can use filterNotNull() method to remove null elements from a Kotlin list.
fun main() {
val theList = listOf("one", "two", null, "four", "five")
val resultList = theList.filterNotNull()

println(resultList)
}
OUTPUT:
[one, two, four, five]

Kotlin mutable List


We can create mutable list using mutableListOf(), later we can use add() to add more
elements in the same list, and we can use remove() method to remove the elements from
the list.
fun main()
{
val theList = mutableSetOf(10, 20, 30)

theList.add(40)
theList.add(50)
println(theList)

theList.remove(10)
theList.remove(30)
println(theList)
}
OUTPUT:
[10, 20, 30, 40, 50]
[20, 40, 50]

1.6 Loops (Iterative statements)


1.6.1 for and while loop

For Loop:
Often when you work with arrays, you need to loop through all of the elements.
To loop through array elements, use the for loop together with the in operator:
fun main()
{
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars)
{
println(x)
}
}

You can loop through all kinds of arrays. In the example above, we used an array of strings.
In the example below, we loop through an array of integers:

PROF. BHUMIKA PATEL 21


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
fun main()
{
val nums = arrayOf(1, 5, 10, 15, 20)
for (x in nums)
{
println(x)
}
}

Kotlin Ranges
With the for loop, you can also create ranges of values with "..":
fun main()
{
for(chars in 'a'..'x')
{ println(chars) }
}

You can also create ranges of numbers:


fun main()
{
for(nums in 5..15)
{ println(nums) }
}

Check if a Value Exists


You can also use the in operator to check if a value exists in a range:
fun main() {
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
println("It exists!")
} else {
println("It does not exist.")
}
}

Kotlin while loop


Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more
readable.

Kotlin While Loop


The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
// code block to be executed
}
Example:
fun main() {
var i = 0
while (i < 5) {
println(i)
i++

PROF. BHUMIKA PATEL 22


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
}
}
The Do..While Loop
The do..while loop is a variant of the while loop. 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.
fun main()
{
var i = 0;
do {
println(i)
i++
}
while (i < 5)
}

1.6.2 break, continue and return


Break Expression
A break expression is used for terminate the nearest enclosing loop. It is almost used with
if-else condition.
Syntax:
for(..){
//body of for
if(checkCondition){
break;
}
}
for loop terminates its loop when if condition execute break expression
Kotlin break example:
fun main(args: Array<String>)
{
for (i in 1..5)
{
if (i == 3)
{
break
}
println(i)
}
}
Output:
1
2

Continue Statement
Kotlin, continue statement is used to repeat the loop. It continues the current flow of the
program and skips the remaining code at specified condition.
The continue statement within a nested loop only affects the inner loop.
Syntax:
for(..){
//body of for above if
if(checkCondition){

PROF. BHUMIKA PATEL 23


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
continue
}
//body of for below if
}

Kotlin continue example


fun main(args: Array<String>)
{
for (i in 1..3)
{
println("i = $i")
if (j == 2)
{ continue }
println("this is below if")
}
}
Output:
i=1
this is below if
i=2
i=3
this is below if

return keyword in Kotlin


In Kotlin, the return keyword is used to exit a function and optionally return a value to the
caller. Here's how it works:
1. Returning a Value:
Kotlin
fun add(a: Int, b: Int): Int {
return a + b
}
The return keyword is followed by the value to be returned.
The function signature specifies the return type (Int in this case).

2. Returning from a Function Early:


Kotlin
fun checkNumber(num: Int): String {
if (num < 0) {
return "Negative number"
} else if (num > 0) {
return "Positive number"
}
return "Zero"
}
return can be used to exit the function before reaching the end, based on certain conditions.

3. Using return in Lambda Expressions:


Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach {
if (it == 3) return@forEach // Non-local return
println(it)
}

PROF. BHUMIKA PATEL 24


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
In a lambda, return by default exits the lambda itself.
To exit the enclosing function from a lambda, use labels like return@forEach.

4. Implicit Return:
Kotlin
fun square(x: Int) = x * x

In single-expression functions, the return keyword can be omitted, and the expression's
value is returned automatically.

 Kotlin Functions
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 Functions are used to perform certain actions, and they are also known as methods.

In Kotlin, functions are declared using fun keyword. There are two types of functions
depending on whether it is available in standard library or defined by user.
1) Standard library function
2) User defined function

Standard Library Function


Kotlin Standard library function is built-in library functions which are implicitly present in
library and available for use.
For example
fun main(args: Array<String>)
{
var number = 25
var result = Math.sqrt(number.toDouble())
print("Square root of $number is $result")
}
Output:
Square root of 25 is 5.

User defined function or Create Your Own Functions


To create your own function, use the fun keyword, and write the name of the function,
followed by parantheses():
Example
Create a function named "myFunction" that should output some text:
fun myFunction() {
println("I just got executed!")
}

Call a Function
Now that you have created a function, you can execute it by calling it.
To call a function in Kotlin, write the name of the function followed by two parantheses ().
In the following example, myFunction() will print some text (the action), when it is called:
fun myFunction() {
println("I just got executed!")
}
fun main() {
myFunction()
}
Function Parameters

PROF. BHUMIKA PATEL 25


A.Y. - 2024-25
TYBCA – SEM5 - 501-02 - Advanced Mobile Computing
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma. Just note that you must
specify the type of each parameter (Int, String, etc).

The following example has a function that takes a String called fname as parameter. When
the function is called, we pass along a first name, which is used inside the function to print
the full name:
fun myFunction(fname: String) {
println(fname + " Doe")
}

fun main() {
myFunction("John")
myFunction("Jane")
myFunction("George")
}

Return Values
In the examples above, we used functions to output a value. In the following example, we
will use a function to return a value and assign it to a variable.
To return a value, use the return keyword, and specify the return type after the function's
parantheses (Int in this example):
Example
A function with one Int parameter, and Int return type:
fun myFunction(x: Int): Int {
return (x + 5)
}

fun main() {
var result = myFunction(3)
println(result)
}

Example
A function with two Int parameters, and Int return type:
fun myFunction(x: Int, y: Int): Int {
return (x + y)
}

fun main() {
var result = myFunction(3, 5)
println(result)
}

PROF. BHUMIKA PATEL 26

You might also like