0% found this document useful (0 votes)
3 views

Android Chapter-1

Kotlin is a cross-platform, statically typed programming language that serves as an alternative to Java for Android app development and is supported by major companies like Google and Amazon. The document covers the basics of Kotlin, including variable declaration, data types, standard input/output operations, and various operators. It also explains decision-making structures in Kotlin, such as if-else expressions, providing examples for better understanding.

Uploaded by

ritenpanchasara
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)
3 views

Android Chapter-1

Kotlin is a cross-platform, statically typed programming language that serves as an alternative to Java for Android app development and is supported by major companies like Google and Amazon. The document covers the basics of Kotlin, including variable declaration, data types, standard input/output operations, and various operators. It also explains decision-making structures in Kotlin, such as if-else expressions, providing examples for better understanding.

Uploaded by

ritenpanchasara
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/ 42

SHREE SWAMI VIVEKANAND COLLEGE

SURENDRANAGAR

Chapter -1 :- Introduction To kotlin Programming

Basics of Kotlin
 Kotlin is a cross-platform programming language that may be used as an
alternative to Java for Android App Development.

 Kotlin is a general-purpose, statically typed, and open-source


programming language. It runs on JVM and can be used anywhere Java is
used today. It can be used to develop Android apps, server-side apps and
much more.

 Kotlin is sponsored by Google, announced as one of the official


languages for Android Development in 2017. Kotlin programming
language is multi-platform, i.e. easily executable on a Java Virtual
Machine.
 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.

 Kotlin is a modern programming language that makes developers happier.


Kotlin is easy to pick up, so you can create powerful applications
immediately.

Kotlin Jobs
 Kotlin is very high in demand and all major companies are moving
towards Kotlin to develop their web and mobile applications.
 Following are the great companies who are using Kotlin:
 Google
 Amazon
 Netflix

1|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 Pinterest
 Uber
 Trello
 Coursera
 Basecamp
 Corda
 JetBrains and many more

Kotlin Variable
 Variable refers to a memory location. It is used to store data. The data of
variable can be changed and reused depending on condition or on
information passed to the program.

 Variable Declaration
Kotlin variable is declared using keyword var and val.

1. var language ="Java"


2. val salary = 30000

 Difference between var and val


1. var (Mutable variable): We can change the value of variable declared
using var keyword later in the program.
2. val (Immutable variable): We cannot change the value of variable
which is declared using val keyword.

Kotlin Data Type


 Data type (basic type) refers to type and size of data associated with
variables and functions. Data type is used for declaration of memory
location of variable which determines the features of data.

2|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 In Kotlin, everything is an object, which means we can call member


function and properties on any variable.
 Kotlin built in data type are categorized as following different categories:

o Number
o Character
o Boolean
o Array
o String

Kotlin Standard Input/Output


 Kotlin standard input output operations are performed to flow byte
stream from input device (keyboard) to main memory and from main
memory to output device (screen).

Kotlin Output :-

Kotlin output operation is performed using the


standardmethods print() and println().

fun main(args: Array<String>) {


println("Hello World!")
print("Welcome to kotlin")
}

Output

Hello World!
Welcome to kotlin

The methods print() and println() are internally call System.out.print() and
System.out.println() respectively.

3|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Difference between print() and println() methods:


o print(): print() method is used to print values provided inside the method
"()".
o println(): println() method is used to print values provided inside the
method "()" and moves cursor to the beginning of next line.

Kotlin Input :-

Kotlin has standard library function readLine() which is used for reads line of
string input from standard input stream. It returns the line read or null.

fun main(args: Array<String>) {

println("Enter your name")


val name = readLine()
println("Enter your age")
var age: Int =Integer.valueOf(readLine())
println("Your name is $name and your age is $age")
}

Output:

Enter your name


Ashutosh
Enter your age
25
Your name is Ashutosh and your age is 25

While using the readLine() function, input lines other than String are explicitly
converted into their corresponding types.

Operators
 An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. Kotlin is rich in built-in operators
and provide the following types of operators:

4|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 Arithmetic Operators
 Relational Operators
 Assignment Operators
 Unary Operators
 Logical Operators
 Bitwise Operations

(a) Kotlin Arithmetic Operators

Kotlin arithmetic operators are used to perform basic mathematical operations


such as addition, subtraction, multiplication and division etc.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from x-y


another

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division x%y


remainder

5|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Example:-
fun main(args: Array<String>) {
val x: Int = 40
val y: Int = 20

println("x + y = " + (x + y))


println("x - y = " + (x - y))
println("x / y = " + (x / y))
println("x * y = " + (x * y))
println("x % y = " + (x % y))
}
Output:-
x + y = 60
x - y = 20
x/y=2
x * y = 800
x%y=0

(b) Kotlin Relational Operators

 Kotlin relational (comparison) operators are used to compare two values,


and returns a Boolean value: either true or false.

Operator Name Example

> greater than x>y

6|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

< less than x<y

>= greater than or equal to x >= y

<= less than or equal to x <= y

== is equal to x == y

!= not equal to x != y

Example:-
fun main(args: Array<String>) {
val x: Int = 40
val y: Int = 20

println("x > y = " + (x > y))


println("x < y = " + (x < y))
println("x >= y = " + (x >= y))
println("x <= y = " + (x <= y))
println("x == y = " + (x == y))
println("x != y = " + (x != y))
}
Output:-
x > y = true
x < y = false
x >= y = true
x <= y = false
x == y = false
x != y = true

7|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

(c) Kotlin Assignment Operators

 Kotlin assignment operators are used to assign values to variables.


 Following is an example where we used assignment operator = to assign
a values into two variables:

fun main(args: Array<String>) {


val x: Int = 40
val y: Int = 20

println("x = " + x)
println("y = " + y)
}
output:
x = 40
y = 20

operators:-

Operator Example Expanded Form

= x = 10 x = 10

+= x += 10 x = x - 10

-= x -= 10 x = x - 10

*= x *= 10 x = x * 10

8|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

/= x /= 10 x = x / 10

%= x %= 10 x = x % 10

Example:-

fun main(args: Array<String>) {


var x: Int = 40

x += 5
println("x += 5 = " + x )

x = 40;
x -= 5
println("x -= 5 = " + x)

x = 40
x *= 5
println("x *= 5 = " + x)

x = 40
x /= 5
println("x /= 5 = " + x)

x = 43
x %= 5
println("x %= 5 = " + x)
}

9|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

output:-
x += 5 = 45
x -= 5 = 35
x *= 5 = 200
x /= 5 = 8
x %= 5 = 3

(d) Kotlin Unary Operators


 The unary operators require only one operand; they perform various
operations such as incrementing/decrementing a value by one, negating
an expression, or inverting the value of a boolean.
 Following is the list of Kotlin Unary Operators:

Operator Name Example

+ unary plus +x

- unary minus -x

++ increment by 1 ++x

-- decrement by 1 --x

! inverts the value of a boolean !x

Example:-
fun main(args: Array<String>) {
var x: Int = 40
var b:Boolean = true

10 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

println("+x = " + (+x))


println("-x = " + (-x))
println("++x = " + (++x))
println("--x = " + (--x))
println("!b = " + (!b))
}
output:-
+x = 40
-x = -40
++x = 41
--x = 40
!b = false
 Here increment (++) and decrement (--) operators can be used as prefix as
++x or --x as well as suffix as x++ or x--. The only difference between the two
forms is that in case we use them as prefix then operator will apply before
expression is executed, but if use them as suffix then operator will apply
after the expression is executed.
(e) Kotlin Logical Operators

 Kotlin logical operators are used to determine the logic between two
variables or values:
 Following is the list of Kotlin Logical Operators:

Operator Name Description Example

&& Logical Returns true if both operands are x && y


and true

|| Logical Returns true if either of the x || y


or operands is true

11 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

! Logical Reverse the result, returns false if !x


not the operand is true

Example:-
fun main(args: Array<String>) {
var x: Boolean = true
var y:Boolean = false

println("x && y = " + (x && y))


println("x || y = " + (x || y))
println("!y = " + (!y))
}
output:-
x && y = false
x || y = true
!y = true

(e) Kotlin Bitwise Operations


 Kotlin does not have any bitwise operators but Kotlin provides a list of
helper functions to perform bitwise operations.
 Following is the list of Kotlin Bitwise Functions:

Function Description Example

shl (bits) signed shift left x.shl(y)

12 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

shr (bits) signed shift right x.shr(y)

ushr (bits) unsigned shift right x.ushr(y)

and (bits) bitwise and x.and(y)

or (bits) bitwise or x.or(y)

xor (bits) bitwise xor x.xor(y)

inv() bitwise inverse x.inv()

Example
fun main(args: Array<String>) {
var x:Int = 60 // 60 = 0011 1100
var y:Int = 13 // 13 = 0000 1101
var z:Int

z = x.shl(2) // 240 = 1111 0000


println("x.shl(2) = " + z)

z = x.shr(2) // 15 = 0000 1111


println("x.shr(2) = " + z)

z = x.and(y) // 12 = 0000 1100


println("x.and(y) = " + z)

z = x.or(y) // 61 = 0011 1101

13 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

println("x.or(y) = " + z)

z = x.xor(y) // 49 = 0011 0001


println("x.xor(y) = " + z)

z = x.inv() // -61 = 1100 0011


println("x.inv() = " + z)
}
output:
x.shl(2) = 240
x.shr(2) = 15
x.and(y) = 12
x.or(y) = 61
x.xor(y) = 49
x.inv() = -61

Decision Making
 In Kotlin, if is an expression is which returns a value. It is used for control
the flow of program structure. There is various type of if expression in
Kotlin.

o if-else expression
o if-else if-else ladder expression
o nested if expression

 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:

14 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

if (condition) {
// code block A to be executed if condition is true
} else {
// code block B to be executed if condition is false
}

 Here if statement is executed and the given condition is checked. If this


condition is evaluated to true then code block A is executed, otherwise
program goes into else part and code block B is executed.

Example
You can try the following 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) {

15 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

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


} else {
// code block B to be executed if condition is false
}
If you're using if as an expression, for example, for returning its value or
assigning it to a variable, the else branch is mandatory.
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

16 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

}
Example
fun main(args: Array<String>) {
val age:Int = 13

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
}
17 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

} else {
// code block D to be executed if condition1 is false
}
Example
fun main(args: Array<String>) {
val age:Int = 20

val result = if (age > 12) {


if ( age > 12 && age < 20 ){
"Teen"
}else{
"Adult"
}
} else {
"Minor"
}
print("The value of result : ")
println(result)
}
output:
The value of result : Adult

What are loops?


 Imagine a situation when you need to print a sentence 20 times on your
screen. You can do it by using print statement 20 times. What about if
you need to print the same sentence one thousand times? This is where
we need to use loops to simplify the programming job. Actually, Loops
are used in programming to repeat a specific block of code until certain
condition is met.

18 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 Kotlin supports various types of loops and in this chapter we are going to
learn Kotlin for loop.
 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#.

 Kotlin does not provide a conventional for loop which is available in C,


C++ and Java etc.

Syntax:-
for (item in collection)
{
// body of loop
}
Iterate Through a Range
fun main(args: Array<String>) {
for (item in 1..5) {
println(item)
}
}
output:
1
2
3
4
5
Let's see one more example where the loop will iterate through another range,
but this time it will step down instead of stepping up as in the above example:
19 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

fun main(args: Array<String>) {


for (item in 5 downTo 1 step 2) {
println(item)
}
}
output:
5
3
1
 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
The syntax of the Kotlin while loop is as follows:

while (condition) {

// body of the loop

When Kotlin program reaches the while loop, it checks the given condition, if
given condition is true then body of the loop gets executed, otherwise program
starts executing code available after the body of the while loop .
Example
Following is an example where the while loop continue executing the body of
the loop as long as the counter variable i is greater than 0:

fun main(args: Array<String>) {

var i = 5;

20 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

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.

The loop will always be executed at least once, even if the condition is false,
because the code block is executed before the condition is tested.

Syntax
The syntax of the Kotlin do...while loop is as follows:

do{

// body of the loop

}while( condition )

When Kotlin program reaches the do...while loop, it directly enters the body of
the loop and executes the available code before it checks for the given

21 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

condition. If it finds given condition is true, then it repeats the execution of the
loop body and continue as long as the given condition is true.
Example
Following is an example where the do...while loop continue executing the body
of the loop as long as the counter variable i is greater than 0:

fun main(args: Array<String>) {

var i = 5;

do{

println(i)

i--

}while(i > 0)

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

22 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

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.
 At a broad level, a function takes some input which is called parameters,
perform certain actions on these inputs and finally returns a value.
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.
Example
fun main(args: Array<String>) {
println("Hello, World!")
}
User-Defined Functions
 Kotlin allows us to create our own function using the keyword fun. A user
defined function takes one or more parameters, perform an action and
return the result of that action as a value.
Syntax:-
fun functionName(){
// body of function
}
 Once we defined a function, we can call it any number of times whenever
it is needed. Following isa simple syntax to call a Kotlin function:
functionName()
Example:-
 Following is an example to define and call a user-defined function which
will print simple "Hello, World!":

23 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

fun main(args: Array<String>)


{
printHello()
}
fun printHello()
{
println("Hello, World!")
}
output:-
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:-
 Following is an example to write a user-defined function which will add
two given numbers and print their sum:
fun main(args: Array<String>) {
val a = 10
val b = 20
printSum(a, b)
}
fun printSum(a:Int, b:Int)
{
println(a + b)
}
output:
30

24 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Return Values
 A kotlin function return a value based on requirement. Again it is very
much optional to return a value.
 To return a value, use the return keyword, and specify the return type
after the function's parantheses
Example:-
 Following is an example to write a user-defined function which will add
two given numbers and return the sum:
fun main(args: Array<String>)
{
val a = 10
val b = 20

val result = sumTwo(a, b)


println( result )

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


val x = a + b

return x
}
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.
25 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

fun sumTwo(a:Int, b:Int):Unit


{
val x = a + b

println( x )
}
The Unit return type declaration is also optional. The above code is equivalent
to:
fun sumTwo(a:Int, b:Int)
{
val x = a + b
println( x )
}
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.
Syntax:-
fun functionName(){
...
functionName()
...
}
Example:-
Following is a Kotlin program to calculate the factorial of number 10:
fun main(args: Array<String>) {
val a = 4

26 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

val result = factorial(a)


println( result )

fun factorial(a:Int):Int{
val result:Int

if( a <= 1){


result = a
}else{
result = a*factorial(a-1)
}

return result
}
output:
24
Kotlin Tail Recursion
 A recursive function is eligible for tail recursion if the function call to
itself is the last operation it performs.
Example:
 Following is a Kotlin program to calculate the factorial of number 10 using
tail recursion. Here we need to ensure that the multiplication is done
before the recursive call, not after.

27 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

fun main(args: Array<String>)


{
val a = 4

val result = factorial(a)


println( result )

}
fun factorial(a: Int, accum: Int = 1): Int
{
val result = a * accum
return if (a <= 1)
{
result
}
else
{
factorial(a - 1, result)
}
}

output:
24

 Kotlin tail recursion is useful while calculating factorial or some other


processing on large numbers. So to
avoide java.lang.StackOverflowError, you must use tail recursion.

28 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Higher-Order Functions
 A higher-order function is a function that takes another function as
parameter and/or returns a function.
Example:
 Following is a function which takes two integer parameters, a and b and
additionally, it takes another function operation as a parameter:
fun main(args: Array<String>)
{
val result = calculate(4, 5, ::sum)
println( result )
}
fun sum(a: Int, b: Int) = a + b
fun calculate(a: Int, b: Int, operation:(Int, Int) -> Int): Int {
return operation(a, b)
}
output:
9
 Here we are calling the higher-order function passing in two integer
values and the function argument ::sum. Here :: is the notation that
references a function by name in Kotlin.
Example:
 more example where a function returns another function. Here we
defined a higher-order function that returns a function. Here (Int) ->
Int represents the parameters and return type of the square function.
fun main(args: Array<String>) {
val func = operation()
println( func(4) )

}
29 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

fun square(x: Int) = x * x

fun operation(): (Int) -> Int {


return ::square
}
output:
9
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.
Syntax:-
{variable with type -> body of the function}
Example:-
fun main(args: Array<String>)
{

val upperCase = { str: String -> str.toUpperCase() }

println( upperCase("hello, world!") )

}
output:
HELLO, WORLD!

30 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

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.
Example:-
fun main(args: Array<String>) {

myFunction({println("Inline function parameter")})

}
inline fun myFunction(function:()-> Unit){
println("I am inline function - A")

function()

println("I am inline function - B")


}
output:
I am inline function - A
Inline function parameter
I am inline function - B

Data Structure Or Collection


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

31 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

 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.
Kotlin Collection Types
Kotlin provides the following types of collection:
 Collection or Immutable Collection
 Mutable Collection
Kotlin Immutable Collection
Immutable Collection or simply calling a Collection interface provides read-only
methods which means once a collection is created, we can not change it
because there is no method available to change the object created.

Collection Types Methods of Immutable Collection

List listOf()
listOf<T>()

Map mapOf()

Set setOf()

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

32 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

println(numbers)
}
When you run the above Kotlin program, it will generate the following output:
[one, two, three, four]
Kotlin Mutable Collection
Mutable collections provides both read and write methods.

Collection Types Methods of Immutable Collection

List ArrayList<T>()
arrayListOf()
mutableListOf()

Map HashMap
hashMapOf()
mutableMapOf()

Set hashSetOf()
mutableSetOf()

Example
fun main() {
val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five")
println(numbers)
}
output:
[one, two, three, four, five]

33 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Inheritance

 Inheritance is an important feature of object oriented programming


language. Inheritance allows to inherit the feature of existing class (or
base or parent class) to new class (or derived class or child class).

 The main class is called super class (or parent class) and the class which
inherits the superclass is called subclass (or child class). The subclass
contains features of superclass as well as its own.

 The concept of inheritance is allowed when two or more classes have


same properties. It allows code reusability. A derived class has only one
base class but may have multiple interfaces whereas a base class may
have one or more derived classes.

 In Kotlin, the derived class inherits a base class using: operator in the class
header (after the derive class name or constructor)

Kotlin open keyword


 As Kotlin classes are final by default, they cannot be inherited simply. We
use the open keyword before the class to inherit a class and make it to
non-final,

For example:

open class Example{


// I can now be extended!
}

Inheritance Example:-

 we declare a class Employee is superclass and Programmer and Salesman


are their subclasses. The subclasses inherit properties name, age and

34 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

salary as well as subclasses containtheir own functionalitieslike


doProgram() and fieldWork().

open class Employee(name: String, age: Int, salary: Float) {


init {
println("Name is $name.")
println("Age is $age")
println("Salary is $salary")
}
}
class Programmer(name: String, age: Int, salary: Float):Employee(name,age,sa
lary){
fun doProgram() {
println("programming is my passion.")
}
}
class Salesman(name: String, age: Int, salary: Float):Employee(name,age,salar
y){
fun fieldWork() {
println("travelling is my hobby.")
}
}
fun main(args: Array<String>){
val obj1 = Programmer("Ashu", 25, 40000f)
obj1.doProgram()
val obj2 = Salesman("Ajay", 24, 30000f)
obj2.fieldWork()
}

Output:

Name is Ashu.
Age is 25
Salary is 40000.0
programming is my passion.
Name is Ajay.
Age is 24
Salary is 30000.0
travelling is my hobby.

35 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Kotlin Abstract class


 A class which is declared with abstract keyword is known as abstract
class. An abstract class cannot be instantiated. Means, we cannot create
object of abstract class. The method and properties of abstract class are
non-abstract unless they are explicitly declared as abstract.

Declaration of abstract class


abstract class A {
var x = 0
abstract fun doSomething()
}

 Abstract classes are partially defined classes, methods and properties


which are no implementation but must be implemented into derived
class. If the derived class does not implement the properties of base class
then is also meant to be an abstract class.

 Abstract class or abstract function does not need to annotate with open
keyword as they are open by default. Abstract member function does not
contain its body. The member function cannot be declared as abstract if
it contains in body in abstract class.

Example:-
abstract class Car{
abstract fun run()
}
class Honda: Car(){
override fun run(){
println("Honda is running safely..")
}
}
fun main(args: Array<String>){
val obj = Honda()

36 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

obj.run();
}

Output:

Honda is running safely..

 A non-abstract open member function can be over ridden in an abstract class.

open class Car {


open fun run() {
println("Car is running..")
}
}
abstract class Honda : Car() {
override abstract fun run()
}
class City: Honda(){
override fun run() {
// TODO("not implemented") //To change body of created functions use F
ile | Settings | File Templates.
println("Honda City is running..")
}
}
fun main(args: Array<String>){
val car = Car()
car.run()
val city = City()
city.run()
}

Output:

Car is running..
Honda City is running..

37 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

Kotlin Interface
 An interface is a blueprint of class.Kotlin interface is similar to Java 8. It
contains abstract method declarations as well as implementation of
method.

Defining Interface

 An interface is defined using the keyword interface.

For example:

interface MyInterface {
val id: Int // abstract property
fun absMethod()// abstract method
fun doSomthing() {
// optional body
}
}

 The methods which are only declared without their method body
are abstract by default.

Why use Kotlin interface?

 Following are the reasons to use interface:

o Using interface supports functionality of multiple inheritance.


o It can be used achieve to loose coupling.
o It is used to achieve abstraction.

Implementing Interfaces
interface MyInterface {
var id: Int // abstract property
fun absMethod():String // abstract method
fun doSomthing() {
println("MyInterface doing some work")
}

38 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

}
class InterfaceImp : MyInterface {
override var id: Int = 101
override fun absMethod(): String{
return "Implementing abstract method.."
}
}
fun main(args: Array<String>) {
val obj = InterfaceImp()
println("Calling overriding id value = ${obj.id}")
obj.doSomthing()
println(obj.absMethod())
}

Output:

Calling overriding id value = 101


MyInterface doing some work
Implementing abstract method..

Implementing multiple interface

 We can implement multiple abstract methods of different interfaces in


same class. All the abstract methods must be implemented in subclass.
The other non-abstract methods of interface can be called from derived
class.
 For example, creating two interface MyInterface1 and MyInterface2 with
abstract methods doSomthing() and absMethod() respectively. These
abstract methods are overridden in derive class MyClass.

interface MyInterface1 {
fun doSomthing()
}
interface MyInterface2 {
fun absMethod()
}
class MyClass : MyInterface1, MyInterface2 {

39 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

override fun doSomthing() {


println("overriding doSomthing() of MyInterface1")
}

override fun absMethod() {


println("overriding absMethod() of MyInterface2")
}
}
fun main(args: Array<String>) {
val myClass = MyClass()
myClass.doSomthing()
myClass.absMethod()
}

Output:

overriding doSomthing() of MyInterface1


overriding absMethod() of MyInterface2

Kotlin Visibility Modifier


Visibility modifiers are the keywords which are used to restrict the use of class,
interface, methods, and property of Kotlin in the application. These modifiers
are used at multiple places such as class header or method body.

In Kotlin, visibility modifiers are categorized into four different types:

o public
o protected
o internal
o private

public modifier

A public modifier is accessible from everywhere in the project. It is a default


modifier in Kotlin. If any class, interface etc. are not specified with any access
modifier then that class, interface etc. are used in public scope.

40 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

protected modifier

A protected modifier with class or interface allows visibility to its class or


subclass only. A protected declaration (when overridden) in its subclass is also
protected modifier unless it is explicitly changed.

internal modifier

The internal modifiers are newly added in Kotlin, it is not available in Java.
Declaring anything makes that field marked as internal field. The internal
modifier makes the field visible only inside the module in which it is
implemented.

private modifier

A private modifier allows the declaration to be accessible only within the block
in which properties, fields, etc. are declare. The private modifier declaration
does not allow to access the outside the scope. A private package can be
accessible within that specific file.

Example of Visibility Modifier


open class Base() {
var a = 1 // public by default
private var b = 2 // private to Base class
protected open val c = 3 // visible to the Base and the Derived class
internal val d = 4 // visible inside the same module
protected fun e() { } // visible to the Base and the Derived class
}

class Derived: Base() {


// a, c, d, and e() of the Base class are visible
// b is not visible
override val c = 9 // c is protected
}

fun main(args: Array<String>) {


val base = Base()
// base.a and base.d are visible
// base.b, base.c and base.e() are not visible
41 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR

val derived = Derived()


// derived.c is not visible
}

42 | P a g e
Prepared By : Bhartiba Parmar

You might also like