You are on page 1of 250

Kotlin First Program Concept

Let's understand the concepts and keywords of Kotlin program 'Hello World.kt'.

fun main(args: Array<String>) {


println("Hello World!")
}

1. The first line of program defines a function called main(). In Kotlin, function is a group of statements that performs
a group of tasks. Functions start with a keyword fun followed by function name (main in this case).

The main () function takes an array of string (Array<String>) as a parameter and returns Unit. Unit is used to
indicate the function and does not return any value (void as in Java). Declaring Unit is an optional, we do not declare
it explicitly.

fun main(args: Array<String>): Unit {


//
}
The main() function is the entry point of the program, it is called first when Kotlin program starts execution.

2. The second line used to print a String "Hello World!". To print standard output we use wrapper println() over
standard Java library functions (System.out.println()).

println("Hello World!")

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.

var language ="Java"


val salary = 30000

The difference between var and val is specified later on this page.

Here, variable language is String type and variable salary is Int type. We don't require specifying the type of variable
explicitly. Kotlin complier knows this by initilizer expression ("Java" is a String and 30000 is an Int value). This is
called type inference in programming.

We can also explicitly specify the type of variable while declaring it.

This page by mytechtalk | Kotlin Variable 1


var language: String ="Java"
val salary: Int = 30000

It is not necessary to initialize variable at the time of its declaration. Variable can be initialized later on when the
program is executed.

var language: String


... ... ...
language = "Java"
val salary: Int
... ... ...
salary = 30000
Difference between var and val
o var (Mutable variable): We can change the value of variable declared using var keyword later in the program.
o val (Immutable variable): We cannot change the value of variable which is declared using val keyword.

Example

var salary = 30000


salary = 40000 //execute
Here, the value of variable salary can be changed (from 30000 to 40000) because variable salary is declared
using var keyword.
val language = "Java"
language = "Kotlin" //Error
Here, we cannot re-assign the variable language from "Java" to "Kotlin" because the variable 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.

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

This page by mytechtalk | Kotlin Data Type 2


Number Types
Number types of data are those which hold only number type data variables. It is further categorized into different
Integer and Floating point.

Data Type Bit Width (Size) Data Range

Byte 8 bit -128 to 127

Short 16 bit -32768 to 32767

Int 32 bit -2,147,483,648 to 2,147,483,647

Long 64 bit -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

Float 32 bit 1.40129846432481707e-45 to 3.40282346638528860e+38

Double 64 bit 4.94065645841246544e-324 to 1.79769313486231570e+308

Character (Char) Data Type


Characters are represented using the keyword Char. Char types are declared using single quotes ('').

Data Type Bit Width (Size) Data Range

Char 4 bit -128 to 127

Example

val value1 = 'A'


//or
val value2: Char
value2= 'A'
This page by mytechtalk | Character (Char) Data Type 3
Boolean Data Types
Boolean data is represented using the type Boolean. It contains values either true or false.

Data Type Bit Width (Size) Data Value

Boolean 1 bit true or false

Example

val flag = true

Array
Arrays in Kotlin are represented by the Array class. Arrays are created using library function arrayOf() and Array()
constructor. Array has get (), set() function, size property as well as some other useful member functions.

Creating Array using library function arrayOf()


The arrayOf() function creates array of wrapper types. The item value are passed inside arrayOf() function like
arrayOf(1,2,3) which creates an array[1,2,3].

The elements of array are accessed through their index values (array[index]). Array index are start from zero.

val id = arrayOf(1,2,3,4,5)
val firstId = id[0]
val lasted = id[id.size-1]

Creating Array using Array() constructor


Creating array using Array() constructor takes two arguments in Array() constructor:

1. First argument as a size of array, and


2. Second argument as the function, which is used to initialize and return the value of array element given its
index.

val asc = Array(5, { i -> i * 2 }) //asc[0,2,4,6,8]

This page by mytechtalk | Data Range 4


String
String in Kotlin is represented by String class. String is immutable, which means we cannot change the elements in
String.

String declaration:

val text ="Hello, JavaTpoint"

Types of String
String are categorize into two types. These are:

1. Escaped String: Escape String is declared within double quote (" ") and may contain escape characters like '\n', '\t',
'\b' etc.

val text1 ="Hello, JavaTpoint"


//or
val text2 ="Hello, JavaTpoint\n"
//or
val text3 ="Hello, \nJavaTpoint"

2. Raw String: Row String is declared within triple quote (""" """). It provides facility to declare String in new lines
and contain multiple lines. Row String cannot contain any escape character.

val text1 ="""


Welcome
To
JavaTpoint
"""

Kotlin Type Conversion


Type conversion is a process in which one data type variable is converted into another data type. In Kotlin,
implicit conversion of smaller data type into larger data type is not supported (as it supports in java). For
example Int cannot be assigned into Long or Double.

In Java
int value1 = 10;
long value2 = value1; //Valid code

This page by mytechtalk | Kotlin Type Conversion 5


In Kotlin
var value1 = 10
val value2: Long = value1 //Compile error, type mismatch

However in Kotlin, conversion is done by explicit in which smaller data type is converted into larger data type
and vice-versa. This is done by using helper function.

var value1 = 10
val value2: Long = value1.toLong()

The list of helper functions used for numeric conversion in Kotlin is given below:

o toByte()

o toShort()

o toInt()

o toLong()

o toFloat()

o toDouble()

o toChar()

Kotlin Type Conversion Example


Let see an example to convert from Int to Long.

fun main(args : Array<String>) {


var value1 = 100
val value2: Long =value1.toLong()
println(value2)
}

We can also converse from larger data type to smaller data type.

fun main(args : Array<String>) {


var value1: Long = 200
val value2: Int =value1.toInt()
println(value2)
}

Kotlin Operator
This page by mytechtalk | Kotlin Operator 6
Operators are special characters which perform operation on operands (values or variable).There are various
kind of operators available in Kotlin.

o Arithmetic operator

o Relation operator

o Assignment operator

o Unary operator

o Bitwise operation

o Logical operator

Arithmetic Operator
Arithmetic operators are used to perform basic mathematical operations such as addition (+), subtraction (-),
multiplication (*), division (/) etc.

Operator Description Expression Translate to

+ Addition a+b a.plus(b)

- Subtraction a-b a.minus(b)

* Multiply a*b a.times(b)

/ Division a/b a.div(b)

% Modulus a%b a.rem(b)

Example of Arithmetic Operator


fun main(args : Array<String>) {
var a=10;
var b=5;
println(a+b);

This page by mytechtalk | Kotlin Operator 7


println(a-b);
println(a*b);
println(a/b);
println(a%b);
}

Output:

15
5
50
2
0

Relation Operator
Relation operator shows the relation and compares between operands. Following are the different relational
operators:

Operator Description Expression Translate to

> greater than a>b a.compateTo(b)>0

< Less than a<b a.compateTo(b)<0

>= greater than or equal to a>=b a.compateTo(b)>=0

<= less than or equal to a<=b a?.equals(b)?:(b===null)

== is equal to a==b a?.equals(b)?:(b===null)

!= not equal to a!=b !(a?.equals(b)?:(b===null))

Example of Relation Operator

fun main(args : Array<String>) {


val a = 5

This page by mytechtalk | Kotlin Operator 8


val b = 10
val max = if (a > b) {
println("a is greater than b.")
a
} else{
println("b is greater than a.")
b
}
println("max = $max")
}

Output:

b is greater than a.
max = 10

Assignment operator
Assignment operator "=" is used to assign a value to another variable. The assignment of value takes from right
to left.

Operator Description Expression Convert to

+= add and assign a+=b a.plusAssign(b)

-= subtract and assign a-=b a.minusAssign(b)

*= multiply and assign a*=b a.timesAssign(b)

/= divide and assign a/=b a.divAssign(b)

%= mod and assign a%=b a.remAssign(b)

Example of Assignment operator

fun main(args : Array<String>) {

This page by mytechtalk | Kotlin Operator 9


var a =20;var b=5
a+=b
println("a+=b :"+ a)
a-=b
println("a-=b :"+ a)
a*=b
println("a*=b :"+ a)
a/=b
println("a/=b :"+ a)
a%=b
println("a%=b :"+ a)

Output:

a+=b :25
a-=b :20
a*=b :100
a/=b :20
a%=b :0

Unary Operator
Unary operator is used with only single operand. Following are some unary operator given below.

Operator Description Expression Convert to

+ unary plus +a a.unaryPlus()

- unary minus -a a.unaryMinus()

++ increment by 1 ++a a.inc()

-- decrement by 1 --a a.dec()

This page by mytechtalk | Kotlin Operator 10


! not !a a.not()

Example of Unary Operator

fun main(args: Array<String>){


var a=10
var b=5
var flag = true
println("+a :"+ +a)
println("-b :"+ -b)
println("++a :"+ ++a)
println("--b :"+ --b)
println("!flag :"+ !flag)
}

Output:

+a :10
-b :-5
++a :11
--b :4
!flag :false

Logical Operator
Logical operators are used to check conditions between operands. List of logical operators are given below.

Operator Description Expression Convert to

&& return true if all expression are true (a>b) && (a>c) (a>b) and (a>c)

|| return true if any expression are true (a>b) || (a>c) (a>b) or(a>c)

! return complement of expression !a a.not()

Example of Logical Operator

This page by mytechtalk | Kotlin Operator 11


fun main(args: Array<String>){
var a=10
var b=5
var c=15
var flag = false
var result: Boolean
result = (a>b) && (a>c)
println("(a>b) && (a>c) :"+ result)
result = (a>b) || (a>c)
println("(a>b) || (a>c) :"+ result)
result = !flag
println("!flag :"+ result)

Output:

(a>b) && (a>c) :false


(a>b) || (a>c) :true
!flag :true

Bitwise Operation
In Kotlin, there is not any special bitwise operator. Bitwise operation is done using named function.

Named Function Description Expression

shl (bits) signed shift left a.shl(b)

shr (bits) signed shift right a.shr(b)

ushr (bits) unsigned shift right a.ushr(b)

and (bits) bitwise and a.and(b)

This page by mytechtalk | Kotlin Operator 12


or (bits) bitwise or a.or(b)

xor (bits) bitwise xor a.xor(b)

inv() bitwise inverse a.inv()

Example of Bitwise Operation

fun main(args: Array<String>){


var a=10
var b=2

println("a.shl(b): "+a.shl(b))
println("a.shr(b): "+a.shr(b))
println("a.ushr(b:) "+a.ushr(b))
println("a.and(b): "+a.and(b))
println("a.or(b): "+a.or(b))
println("a.xor(b): "+a.xor(b))
println("a.inv(): "+a.inv())

Output:

a.shl(b): 40
a.shr(b): 2
a.ushr(b:) 2
a.and(b): 2
a.or(b): 10
a.xor(b): 8
a.inv(): -11

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 standard methods print() and println(). Let's see an example:

fun main(args: Array<String>) {


println("Hello World!")
print("Welcome to JavaTpoint")

This page by mytechtalk | Kotlin Standard Input/Output 13


}

Output

Hello World!
Welcome to JavaTpoint

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

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.

Example

fun main(args: Array<String>){


println(10)
println("Welcome to JavaTpoint")
print(20)
print("Hello")
}

Output:

10
Welcome to JavaTpoint
20Hello

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. Let's see an example:

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:

This page by mytechtalk | Kotlin Standard Input/Output 14


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.

To input other data type rather than String, we need to use Scanner object of java.util.Scanner class from Java
standard library.

Example Getting Integer Input

import java.util.Scanner
fun main(args: Array<String>) {
val read = Scanner(System.`in`)
println("Enter your age")
var age = read.nextInt()
println("Your input age is "+age)
}

Output:

Enter your age


25
Your input age is 25

Here nextInt() is a method which takes integer input and stores in integer variable. The other data types Boolean,
Float, Long and Double uses nextBoolean(), nextFloat(), nextLong() and nextDouble() to get input from user.

Kotlin Comment
Comments are the statements that are used for documentation purpose. Comments are ignored by compiler so
that don't execute. We can also used it for providing information about the line of code. There are two types of
comments in Kotlin.

1. Single line comment.

2. Multi line comment.

Single line comment


Single line comment is used for commenting single line of statement. It is done by using '//' (double slash). For
example:

fun main(args: Array<String>) {

This page by mytechtalk | Kotlin Comment 15


// this statement used for print
println("Hello World!") }

Output

Hello World!

Multi line comment


Multi line comment is used for commenting multiple line of statement. It is done by using /* */ (start with slash
strict and end with star slash). For example:

fun main(args: Array<String>) {


/* this statement
is used
for print */
println("Hello World!")
}

Output:

Hello World!

Kotlin if Expression
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

Traditional if Statement
Syntax of traditional if statement

if(condation){
//code statement
}

Syntax of traditional if else statement

This page by mytechtalk | Kotlin if Expression 16


if(condation){
//code statement
}
else{
//code statement
}

Kotlin if-else Expression


As if is an expression it is not used as standalone, it is used with if-else expression and the result of an if-else
expression is assign into a variable.

Syntax of if-else expression

val returnValue = if (condation) {


//code statement
} else {
// code statement
}
println(returnValue)

Kotlin if-else Expression Example

Let's see an example of if-else expression.

fun main(args: Array<String>) {


val num1 = 10
val num2 =20
val result = if (num1 > num2) {
"$num1 is greater than $num2"
} else {
"$num1 is smaller than $num2"
}
println(result)
}

Output:

This page by mytechtalk | Kotlin if Expression 17


10 is smaller than 20

We can remove the curly braces of if-else body by writing if expression in only one statement.

For example:

fun main(args: Array<String>) {


val num1 = 10
val num2 =20
val result = if (num1 > num2) "$num1 is greater than $num2" else "$num1 is smaller than $num2"
println(result)
}

Using if-else expression in one single line statement is like ternary operator in Java. Kotlin does not support
any ternary operator.

Kotlin if-else if-else Ladder Expression


Let's see an example of if-else if-else ladder expression.

fun main(args: Array<String>) {


val num = 10
val result = if (num > 0){
"$num is positive"
}else if(num < 0){
"$num is negative"
}else{
"$num is zero"
}
println(result)
}

Output:

10 is positive

This page by mytechtalk | Kotlin if Expression 18


Kotlin Nested if Expression
Let's see an example of nested if expression.

fun main(args: Array<String>) {


val num1 = 25
val num2 = 20
val num3 = 30
val result = if (num1 > num2){

val max = if(num1 > num3){


num1
}else{
num3
}
"body of if "+max
}else if(num2 > num3){
"body of else if"+num2
}else{
"body of else "+num3
}
println("$result")
}

Output:

body of if 30

Kotlin when Expression


Kotlin, when expression is a conditional expression which returns the value. Kotlin, when expression is
replacement of switch statement. Kotlin, when expression works as a switch statement of other language (Java,
C++, C).

Using when as an Expression


Let's see a simple example of when expression.

This page by mytechtalk | Kotlin when Expression 19


fun main(args: Array<String>){
var number = 4
var numberProvided = when(number) {
1 -> "One"
2 -> "Two"
3 -> "Three"
4 -> "Four"
5 -> "Five"
else -> "invalid number"
}
println("You provide $numberProvided")
}

Output:

You provide Four

Using when Without Expression


It is not mandatory to use when as an expression, it can be used as normally as it used in other language.

For Example

fun main(args: Array<String>){

var number = 4
when(number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
4 -> println("Four")
5 -> println("Five")
else -> println("invalid number")
}

Output:

Four

This page by mytechtalk | Kotlin when Expression 20


Multiple Statement of when Using Braces
We can use multiple statement enclosed within block of condition.

For Example

fun main(args: Array<String>){


var number = 1
when(number) {
1 -> {
println("Monday")
println("First day of the week")
}
7 -> println("Sunday")
else -> println("Other days")
}
}

Output:

Monday
First day of the week

Multiple branches of when


We can use multiple branches of condition separated with a comma. It is used, when we need to run a same logic
for multiple choices.

fun main(args: Array<String>){


var number = 8
when(number) {
3, 4, 5, 6 ->
println("It is summer season")
7, 8, 9 ->
println("It is rainy season")
10, 11 ->
println("It is autumn season")
12, 1, 2 ->
println("It is winter season")
else -> println("invalid input")
}

This page by mytechtalk | Kotlin when Expression 21


}

Output:

It is rainy season

Using when in the range


The when expression also check the ranges of input provided in when condition. A range is created using ..
(double dot) operator. The in operator is used to check if a value belongs to a range.

For Example:

fun main(args: Array<String>){


var number = 7
when(number) {
in 1..5 -> println("Input is provided in the range 1 to 5")
in 6..10 -> println("Input is provided in the range 6 to 10")
else -> println("none of the above")
}
}

Output:

Input is provided in the range 6 to 10

Kotlin for Loop


Kotlin for loop is used to iterate a part of program several times. It iterates through arrays, ranges, collections, or
anything that provides for iterate. Kotlin for loop is equivalent to the foreach loop in languages like C#.

Syntax of for loop in Kotlin:

for (item in collection){


//body of loop
}

Iterate through array


Let's see a simple example of iterating the elements of array.

This page by mytechtalk | Kotlin for Loop 22


fun main(args : Array<String>) {
val marks = arrayOf(80,85,60,90,70)
for(item in marks){
println(item)
}
}

Output:

80
85
60
90
70

If the body of for loop contains only one single line of statement, it is not necessary to enclose within curly
braces {}.

fun main(args : Array<String>) {


val marks = arrayOf(80,85,60,90,70)
for(item in marks)
println(item)
}

The elements of an array are iterated on the basis of indices (index) of array. For example:

fun main(args : Array<String>) {

val marks = arrayOf(80,85,60,90,70)


for(item in marks.indices)
println("marks[$item]: "+ marks[item])
}

Output:

marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70

Iterate through range


Let's see an example of iterating the elements of range.

This page by mytechtalk | Kotlin for Loop 23


fun main(args : Array<String>) {

print("for (i in 1..5) print(i) = ")


for (i in 1..5) print(i)
println()
print("for (i in 5..1) print(i) = ")
for (i in 5..1) print(i) // prints nothing
println()
print("for (i in 5 downTo 1) print(i) = ")
for (i in 5 downTo 1) print(i)
println()
print("for (i in 5 downTo 2) print(i) = ")
for (i in 5 downTo 2) print(i)
println()
print("for (i in 1..5 step 2) print(i) = ")
for (i in 1..5 step 2) print(i)
println()
print("for (i in 5 downTo 1 step 2) print(i) = ")
for (i in 5 downTo 1 step 2) print(i)
}

Output:

for (i in 1..5) print(i) = 12345


for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 5 downTo 2) print(i) = 5432
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531

Kotlin while Loop


The while loop is used to iterate a part of program several time. Loop executed the block of code until the
condition has true. Kotlin while loop is similar to Java while loop.

Syntax

while(condition){

This page by mytechtalk | Kotlin while Loop 24


//body of loop
}

Example of while Loop


Let's see a simple example of while loop printing value from 1 to 5.

fun main(args: Array<String>){


var i = 1
while (i<=5){
println(i)
i++
}
}

Output:

1
2
3
4
5

Kotlin Infinite while Loop


The while loop executes a block of code to infinite times, if while condition remain true.

For example:

fun main(args: Array<String>){


while (true){
println("infinite loop")
}
}

Output:

infinite loop
infinite loop
infinite loop
.
.
.
.
infinite loop
infinite loop

This page by mytechtalk | Kotlin while Loop 25


infinite loop
infinite loop
infinite loop
infinite loop

Kotlin do-while Loop


The do-while loop is similar to while loop except one key difference. A do-while loop first execute the body
of do block after that it check the condition of while.

As a do block of do-while loop executed first before checking the condition, do-while loop execute at least once
even the condition within while is false. The while statement of do-while loop end with ";" (semicolon).

Syntax

do{
//body of do block
}
while(condition);

Example of do -while loop

Let's see a simple example of do-while loop printing value 1 to 5.

fun main(args: Array<String>){


var i = 1
do {
println(i)
i++
}
while (i<=5);
}

Output:

1
2
3
4
5

Example of do -while loop even condition of while if false

This page by mytechtalk | Kotlin while Loop 26


In this example do-while loop execute at once time even the condition of while is false.

fun main(args: Array<String>){


var i = 6
do {
println(i)
i++
}
while (i<=5);
}

Output:

Kotlin Return and Jump


There are three jump expressions in Kotlin. These jump expressions are used for control the flow of program
execution. These jump structures are:

o break

o continue

o return

Break Expression
A break expression is used for terminate the nearest enclosing loop. It is almost used with if-else condition.

For example:

for(..){
//body of for
if(checkCondition){
break;
}
}

In the above example, for loop terminates its loop when if condition execute break expression.

Kotlin break example:

This page by mytechtalk | Kotlin Return and Jump 27


fun main(args: Array<String>) {
for (i in 1..5) {
if (i == 3) {
break
}
println(i)
}
}

Output:

1
2

In the above example, when the value of i became equal to 3 and satisfy the if condition(i==3) than the break
expression execute and terminate for loop.

Kotlin Labeled break Expression


Labeled is the form of identifier followed by the @ sign, for example abc@, test@. To make an expression as
label, we just put a label in front of expression.

Kotlin labeled break expression is used to terminate the specific loop. This is done by using break expression
with @ sign followed by label name (break@loop).

Kotlin labeled break example

fun main(args: Array<String>) {


loop@ for (i in 1..3) {
for (j in 1..3) {
println("i = $i and j = $j")
if (i == 2)
break@loop
}
}
}

Output:

i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 2 and j = 1

This page by mytechtalk | Kotlin Return and Jump 28


In the above example, when the value of i became 2 and satisfy the if condition which execute break expression
followed by labeled name. The break expression followed by labeled name terminates the body of label
identifier.

Kotlin continue Jump Structure


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.

For example

for(..){
//body of for above if
if(checkCondition){
continue
}
//body of for below if
}

In the above example, for loop repeat its loop when if condition execute continue. The continue statement makes
repetition of loop without executing the below code of if condition.

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

This page by mytechtalk | Kotlin continue Jump Structure 29


Kotlin Labeled continue Expression
Labeled is the form of identifier followed by the @ sign, for example abc@, test@. To make an expression as
label, we just put a label in front of expression.

Kotlin, labeled continue expression is used for repetition of specific loop (labeled loop). This is done by using
continue expression with @ sign followed by label name (continue@labelname).

Kotlin labeled continue example

1. fun main(args: Array<String>) {


2. labelname@ for (i in 1..3) {
3. for (j in 1..3) {
4. println("i = $i and j = $j")
5. if (i == 2) {
6. continue@labelname
7. }
8. println("this is below if")
9. }
10. }
11. }

Output:

i = 1 and j = 1
this is below if
i = 1 and j = 2
this is below if
i = 1 and j = 3
this is below if
i = 2 and j = 1
i = 3 and j = 1
this is below if
i = 3 and j = 2
this is below if
i = 3 and j = 3
this is below if

Kotlin Function
Function is a group of inter related block of code which performs a specific task. Function is used to break a
program into different sub module. It makes reusability of code and makes program more manageable.

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.

o Standard library function

This page by mytechtalk | Kotlin Function 30


o 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

1. fun main(args: Array<String>){


2. var number = 25
3. var result = Math.sqrt(number.toDouble())
4. print("Square root of $number is $result")
5. }

Output:

Square root of 25 is 5.0

o Here, sqrt() is a library function which returns square root of a number (Double value).

o print() library function which prints a message to standard output stream.

User defined Function


User defined function is a function which is created by user. User defined function takes the parameter(s),
perform an action and return the result of that action as a value.

Kotlin functions are declared using the fun keyword. For example:

1. fun functionName(){
2. // body of function
3. }

We have to call the function to run codes inside the body of the function.

1. functionName()

Kotlin simple function example


1. fun main(args: Array<String>){
2. sum()
3. print("code after sum")
4. }
5. fun sum(){

This page by mytechtalk | Kotlin Function 31


6. var num1 =5
7. var num2 = 6
8. println("sum = "+(num1+num2))
9. }

Output:

sum = 11
code after sum

Kotlin Parameterize Function and Return Value


Functions are also takes parameter as arguments and return value. Kotlin functions are defined using Pascal
notation, i.e. name:type (name of parameter and its type). Parameters in function are separated using commas.

If a function does not returns any value than its return type is Unit. It is optional to specify the return type of
function definition which does not returns any value.

1. fun functionName(number1: Int, number2: Int){


2. .. .. ..
3. }
4. .. .. ..
5. functionName(value1, value2)
6. .. .. ..

Kotlin parameterize function example


1. fun main(args: Array<String>){
2. val result = sum(5, 6)
3. print(result)
4. }
5. fun sum(number1: Int, number2:Int): Int{
6. val add = number1+number2
7. return add
8. }

Output:

11

Kotlin Recursion Function


This page by mytechtalk | Kotlin Recursion Function 32
Recursion function is a function which calls itself continuously. This technique is called recursion.

Syntax

1. fun functionName(){
2. .. .. ..
3. functionName() //calling same function
4. }

Kotlin recursion function example 1: Finite times


Let's see an example of recursion function printing count.

1. var count = 0
2. fun rec(){
3. count++;
4. if(count<=5){
5. println("hello "+count);
6. rec();
7. }
8. }
9. fun main(args: Array<String>) {
10. rec();
11. }

Output:

hello 1
hello 2
hello 3
hello 4
hello 5

Kotlin recursion function example 2: Factorial Number


Let's see an example of recursion function calculating factorial of number.

1. fun main(args: Array<String>) {


2. val number = 5
3. val result: Long
4. result = factorial(number)
5. println("Factorial of $number = $result")
6. }

This page by mytechtalk | Kotlin Recursion Function 33


7.
8. fun factorial(n: Int): Long {
9. return if(n == 1){
10. n.toLong()
11. }
12. else{
13. n*factorial(n-1)
14. }
15. }

Output:

Factorial of 5 = 120

Working process of above factorial example

1. factorial(5)
2. factorial(4)
3. factorial(3)
4. factorial(2)
5. factorial(1)
6. return 1
7. return 2*1 = 2
8. return 3*2 = 6
9. return 4*6 = 24
10. return 5*24 = 120

Kotlin Tail Recursion


Before we will discuss about the tail recursion, let's try to make an example which calculate sum of nth (100000
larger number) using general (normal) recursion.

General Recursion
Let's see an example of calculating sum of nth (100000 larger number) using general (normal) recursion.

1. fun main(args: Array<String>) {


2. var result = recursiveSum(100000)
3. println(result)

This page by mytechtalk | Kotlin Recursion Function 34


4. }
5. fun recursiveSum(n: Long) : Long {
6. return if (n <= 1) {
7. n
8. } else {
9. n + recursiveSum(n - 1)
10. }
11. }

Output:

Exception in thread "main" java.lang.StackOverflowError

The above example throws an exception of "java.lang.StackOverflowError". This is because the compiler is
unable to call large number of recursive function call.

Tail Recursion
Tail recursion is a recursion which performs the calculation first, then makes the recursive call. The result of
current step is passed into the next recursive call.

Tail recursion follows one rule for implementation. This rule is as follow:

The recursive call must be the last call of the method. To declare a recursion as tail recursion we need to
use tailrec modifier before the recursive function.

Kotlin Tail Recursion Example 1: calculating sun of nth(100000)


number
Let's see an example of calculating sum of nth (100000 larger number) using tail recursion.

1. fun main(args: Array<String>) {


2. var number = 100000.toLong()
3. var result = recursiveSum(number)
4. println("sun of upto $number number = $result")
5. }
6. tailrec fun recursiveSum(n: Long, semiresult: Long = 0) : Long {
7. return if (n <= 0) {
8. semiresult
9. } else {
10. recursiveSum( (n - 1), n+semiresult)
11. }

This page by mytechtalk | Kotlin Recursion Function 35


12. }

Output:

sun of upto 100000 number = 5000050000

Kotlin Tail Recursion Example 2: calculating factorial of number


Let's see an example of calculating factorial of number using tail recursion.

1. fun main(args: Array<String>) {


2. val number = 4
3. val result: Long
4. result = factorial(number)
5. println("Factorial of $number = $result")
6. }
7.
8. tailrec fun factorial(n: Int, run: Int = 1): Long {
9. return if (n == 1){
10. run.toLong()
11. } else {
12. factorial(n-1, run*n)
13. }
14. }

Output:

Factorial of 4 = 24

Kotlin Default and Named Argument


Kotlin Default Argument
Kotlin provides a facility to assign default argument (parameter) in a function definition.

If a function is called without passing any argument than default argument are used as parameter of function
definition. And when a function is called using argument, than the passing argument is used as parameter in
function definition.

Default argument example 1: passing no argument in function call


1. fun main(args: Array<String>) {

This page by mytechtalk | Kotlin Default and Named Argument 36


2. run()
3. }
4. fun run(num:Int= 5, latter: Char ='x'){
5. print("parameter in function definition $num and $latter")
6. }

Output:

parameter in function definition 5 and x

In the above program, run() function calls with no argument, the default parameter are used in function
definition.

Default argument example 2: passing some argument in function call


1. fun main(args: Array<String>) {
2. run(3)
3. }
4. fun run(num:Int= 5, latter: Char ='x'){
5. print("parameter in function definition $num and $latter")
6. }

Output:

parameter in function definition 3 and x

In the above program, run() function calls with one (first) argument, the first parameter of the function definition
is uses the value passed to the function. And the second parameter is uses as a default argument.

Default argument example 3: passing all argument in function call


1. fun main(args: Array<String>) {
2. run(3,'a')
3. }
4. fun run(num:Int= 5, latter: Char ='x'){
5. print("parameter in function definition $num and $latter")
6. }

Output:

parameter in function definition 3 and a

As all the arguments are passed in run() function call, the parameters of function definition uses the argument
passed in function call.

This page by mytechtalk | Kotlin Default and Named Argument 37


Kotlin Named Argument
Before we will discuss about the named parameter, let's do some modify in the above program.

For example:

1. fun main(args: Array<String>) {


2. run('a')
3. }
4. fun run(num:Int= 5, latter: Char ='x'){
5. print("parameter in function definition $num and $latter")
6. }

Output:

Error: Kotlin: The character literal does not conform to the expected type Int

Here, we are try to pass parameter 'a' from function call to function definition in the second argument. But
compiler assumes that the parameter 'a' (Char type) passed for first argument (Int type) this causes error in
program.

Named Argument
To solve the above problem a named argument is used.

A named argument is an argument in which we define the name of argument in the function call. The name
defined to argument of function call checks the name in the function definition and assign to it.

Kotlin Named Argument Example

1. fun main(args: Array<String>) {


2. run(latter='a')
3. }
4. fun run(num:Int= 5, latter: Char ='x'){
5. print("parameter in function definition $num and $latter")
6. }

Output:

parameter in function definition 5 and a

Kotlin Lambda Function


This page by mytechtalk | Kotlin Lambda Function 38
Lambda is a function which has no name. Lambda is defined with a curly braces {} which takes variable as a
parameter (if any) and body of function. The body of function is written after variable (if any) followed by -
> operator.

Syntax of lambda
1. { variable -> body_of_function}

Before we talk about lambda, let's see a simple example of addition of two numbers using normal function.

Normal function: addition of two numbers


In this example, we create a function addNumber() passing two arguments (a,b) calling from the main function.

1. fun main(args: Array<String>){


2. addNumber(5,10)
3. }
4. fun addNumber(a: Int, b: Int){
5. val add = a + b
6. println(add)
7. }

Output:

15

Lambda function: addition of two numbers


The above program will be rewritten using lambda function as follow:

1. fun main(args: Array<String>){


2. val myLambda: (Int) -> Unit= {s: Int -> println(s) } //lambda function
3. addNumber(5,10,myLambda)
4. }
5. fun addNumber(a: Int, b: Int, mylambda: (Int) -> Unit ){ //high level function lambda as parameter
6. val add = a + b
7. mylambda(add) // println(add)
8. }

Output:

15

In the above program we create a lambda expression {s: Int -> println(s) } with its return type Unit. The lambda
function is padded as an parameter in high level function addNumber(5,10,myLambda). The
This page by mytechtalk | Kotlin Lambda Function 39
variable mylambda in function definition is actually a lambda function. The functionality (body) of mylambda is
already given in lambda function.

Higher order function


High order function (Higher level function) is a function which accepts function as a parameter or returns a
function or can do both. Means, instead of passing Int, String, or other types as a parameter in a function we can
pass a function as a parameter in other function.

Let's see the following example:

1. fun myFun(org: String,portal: String, fn: (String,String) -> String): Unit {


2. val result = fn(org,portal)
3. println(result)
4. }

In this above example, we defined a function myFun() with three parameters. The first and second parameter take
String and the third parameter as a type of function from String to String. The parameter String to String type
means function takes string as an input and returns output as string types.

To call this above function, we can pass function literal or lambda. For example:

1. fun myFun(org: String,portal: String, fn: (String,String) -> String): Unit {


2. val result = fn(org,portal)
3. println(result)
4. }
5.
6. fun main(args: Array<String>){
7. val fn:(String,String)->String={org,portal->"$org develop $portal"}
8. myFun("sssit.org","javatpoint.com",fn)
9. }

Output:

sssit.org develop javatpoint.com

The above higher order function can also be called in another ways as below mention code in main() function:

myFun("sssit.org","javatpoint.com",{org,portal->"$org develop $portal"})

This page by mytechtalk | Kotlin Lambda Function 40


Inline Function
An inline function is declare with a keyword inline. 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.

The virtual function or local function cannot be declared as inline. Following are some expressions and
declarations which are not supported anywhere inside the inline functions:

o Declaration of local classes

o Declaration of inner nested classes

o Function expressions

o Declarations of local function

o Default value for optional parameters

Let's see the basic example of inline function:

1. fun main(args: Array<String>) {


2. inlineFunction({ println("calling inline functions")})
3. }
4.
5. inline fun inlineFunction(myFun: () -> Unit ) {
6. myFun()
7. print("code inside inline function")
8. }

Output:

calling inline functions


code inside inline function

Non local control flow


From inline function, we can return from lambda expression itself. This will also lead to exit from the function in
which inline function was called. The function literal is allowed to have non local return statements in such case.

1. fun main(args: Array<String>) {


2. inlineFunction({ println("calling inline functions")
3. return},{ println("next parameter in inline functions")})
4. }
5.
6. inline fun inlineFunction(myFun: () -> Unit, nxtFun: () -> Unit) {

This page by mytechtalk | Inline Function 41


7. myFun()
8. nxtFun()
9. print("code inside inline function")
10. }

Output:

calling inline functions

crossinline annotation
To prevent return from lambda expression and inline function itself, we can mark the lambda expression
as crossinline. This will throw a compiler error if it found a return statement inside that lambda expression.

1. fun main(args: Array<String>) {


2. inlineFunction({ println("calling inline functions")
3. return // compile time error
4. },{ println("next parameter in inline functions")})
5. }
6.
7. inline fun inlineFunction(crossline myFun: () -> Unit, nxtFun: () -> Unit) {
8. myFun()
9. nxtFun()
10. print("code inside inline function")
11. }

noinline modifier
In inline function, when we want some of lambdas passed in inline function to be an inlined, mark other function
parameter with noinline modifier. This is used to set expressions not to be inlined in the call.

1. fun main(args: Array<String>) {


2. inlineFunctionExample({ println("calling inline functions")},
3. { println("next parameter in inline functions")} )
4.
5. println("this is main function closing")
6. }
7.
8. inline fun inlineFunctionExample(myFun: () -> Unit, noinline nxtFun: () -> Unit ) {
9. myFun()
10. nxtFun()
This page by mytechtalk | Inline Function 42
11. println("code inside inline function")
12. }

Output:

calling inline functions


next parameter in inline functions
code inside inline function
this is main function closing

If an inline function does not contain any noinline function parameter and no reified type parameters then
compiler will generate a warning.

next →← prev

Kotlin Array
Array is collection of similar data types either of Int, String etc. Array in Kotlinis mutable in nature with
fixed size which means we can perform both read and write operations on elements of array.

Constructor of array:
Array constructor is declared with specified size and init function. The init function is used to returns the
elements of array with their index.

1. Array(size: Int, init: (Int) -> T)

Kotlin Array can be created


using arrayOf(), intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), byteArray
Of() functions.

Kotlin array declaration - using arrayOf() function


1. var myArray1 = arrayOf(1,10,4,6,15)
2. var myArray2 = arrayOf<Int>(1,10,4,6,15)
3. val myArray3 = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")
4. var myArray4= arrayOf(1,10,4, "Ajay","Prakesh")

Kotlin array declaration - using intArrayOf() function


1. var myArray5: IntArray = intArrayOf(5,10,20,12,15)
This page by mytechtalk | Kotlin Array 43
Modify and access elements of array
Kotlin has set() and get() functions that can direct modify and access the particular element of array
respectively.

The set() function is used to set element at particular index location. This is also done with assigning element
at array index. Array get() function is used to get element from specified index.

Kotlin array set() function example


1. fun main(args: Array<String>) {
2. val array1 = arrayOf(1,2,3,4)
3. val array2 = arrayOf<Long>(11,12,13,14)
4. array1.set(0,5)
5. array1[2] = 6
6.
7. array2.set(2,10)
8. array2[3] = 8
9.
10. for(element in array1){
11. println(element)
12. }
13. println()
14. for(element in array2){
15. println(element)
16. }
17. }

Output:

11

12

This page by mytechtalk | Kotlin Array 44


10

Kotlin array get() function example


1. fun main(args: Array<String>) {
2. val array1 = arrayOf(1,2,3,4)
3. val array2 = arrayOf<Long>(11,12,13,14)
4. println(array1.get(0))
5. println(array1[2])
6. println()
7. println(array2.get(2))
8. println(array2[3])
9.
10. }

Output:

13

14

Kotlin Array Example 1:


In this example, we are simply initialize an array of size 5 with default value as 0 and traverse its elements.
The index value of array starts from 0. First element of array is placed at index value 0 and last element at
one less than the size of array.

1. fun main(args: Array<String>){


2. var myArray = Array<Int>(5){0}
3.
4. for(element in myArray){
5. println(element)
6. }
7. }

This page by mytechtalk | Kotlin Array 45


Output:

Kotlin Array Example 2:


We can also rewrite the value of array using its index value. Since, we can able to modify the value of array,
so array is called as mutable property.

For example:

1. fun main(args: Array<String>){


2. var myArray = Array<Int>(5){0}
3.
4. myArray[1]= 10
5. myArray[3]= 15
6.
7. for(element in myArray){
8. println(element)
9. }
10. }

Output:

10

15

This page by mytechtalk | Kotlin Array 46


Kotlin Array Example 3 - using arrayOf() and intArrayOf()
function:
Array in Kotlin can also be declared using library functions such as arrayOf(), intArrayOf(), etc. Let's see the
example of array using arrayOf() and intArrayOf() function.

1. fun main(args: Array<String>){


2. val name = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")
3. var myArray2 = arrayOf<Int>(1,10,4,6,15)
4. var myArray3 = arrayOf(5,10,20,12,15)
5. var myArray4= arrayOf(1,10,4, "Ajay","Prakesh")
6. var myArray5: IntArray = intArrayOf(5,10,20,12,15)
7.
8. for(element in name){
9. println(element)
10. }
11.
12. println()
13. for(element in myArray2){
14. println(element)
15. }
16. println()
17. for(element in myArray3){
18. println(element)
19. }
20. println()
21. for(element in myArray4){
22. println(element)
23. }
24. println()
25. for(element in myArray5){
26. println(element)
27. }
28.
29. }

Output:
This page by mytechtalk | Kotlin Array 47
Ajay

Prakesh

Michel

John

Sumit

10

15

10

20

12

15

10

Ajay

Prakesh

10

15

20

25

Kotlin Array Example 4


Suppose when we try to insert an element at index position greater than array size then what will happen?

This page by mytechtalk | Kotlin Array 48


It will throw an ArrayIndexOutOfBoundException. This is because the index value is not present at which we
tried to insert element. Due to this, array is called fixed size length. For example:

1. fun main(args: Array<String>){


2. var myArray5: IntArray = intArrayOf(5,10,20,12,15)
3.
4. myArray5[6]=18 // ArrayIndexOutOfBoundsException
5. for(element in myArray5){
6. println(element)
7. }
8. }

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

at ArrayListKt.main(Array.kt:4)

Kotlin Array Example 5 - traversing using range:


The Kotlin's array elements are also traversed using index range (minValue..maxValue) or
(maxValue..minValue). Let's see an example of array traversing using range.

1. fun main(args: Array<String>){


2. var myArray5: IntArray = intArrayOf(5,10,20,12,15)
3.
4. for (index in 0..4){
5. println(myArray5[index])
6. }
7. println()
8. for (index in 0..myArray5.size-1){
9. println(myArray5[index])
10. }
11. }

Output:

10

This page by mytechtalk | Kotlin Array 49


20

12

15

10

20

12

15

Kotlin String
The String class represents an array of char types. Strings are immutable which means the length and elements
cannot be changed after their creation.

1. val ch = charArrayOf('h', 'e', 'l', 'l', 'o')


2. val st = String(ch)

Unlike Java, Kotlin does not require a new keyword to instantiate an object of a String class. A String can be
simply declared within double quote (" ") known as escaped string or triple quote(""" """) known as raw string.

1. val str1 = "Hello, javaTpoint"


2. val str2 = """Welcome To JavaTpoint"""

Kotlin String Property


Property Description

length: Int It returns the length of string sequence.

indices: IntRange It returns the ranges of valid character indices from current char sequence.

This page by mytechtalk | Kotlin String 50


lastIndex: Int It returns the index of last character from char sequence.

String Function
Functions Description

compareTo(other: String): Int It compares the current object with specified object for order. It
returns zero if current is equals to specified other object.

get(index: Int): Char It returns the character at given index from the current character
sequence.

plus(other: Any?): String It returns the concatenate string with the string representation of
the given other string.

subSequence(startIndex: Int,endIndex: Int): It returns the new character sequence from current character
CharSequence sequence, starting from startIndex to endIndex.

CharSequence.contains(other: CharSequence, It returns true if the character sequence contains the other
ignoreCase: Boolean = false):Boolean specified character sequence.

CharSequence.count(): Int It returns the length of char sequence.

String.drop(n: Int): String It returns a string after removing the first n character.

String.dropLast(n: Int): String It returns a string after removing the last n character.

String.dropWhile It returns a character sequence which contains all the characters,


(predicate: (Char) -> Boolean except first characters which satisfy the given predicate.
): String

This page by mytechtalk | Kotlin String 51


CharSequence.elementAt(index: Int): Char It returns a character at the given index or throws
an IndexOutOfBoundsException if the index does not exist in
character sequence.

CharSequence.indexOf(char: Char, startIndex: It returns the index of first occurrence of the given character,
Int = 0, starting from the given index value.
ignoreCase: Boolean = false
): Int

CharSequence.indexOfFirst( It returns the index of first character which match the given
predicate: (Char) -> Boolean predicate, or -1 if the character sequence not contains any such
): Int character.

CharSequence.indexOfLast( It returns the index of last character which match the given
predicate: (Char) -> Boolean predicate, or -1 if the character sequence not contains any such
): Int character.

CharSequence.getOrElse(index: Int, It returns the character at specified index or the result of calling
defaultValue: (Int) ->Char): Char the defaultValue function if the index is out of bound of current
character sequence.

CharSequence.getOrNull(index: Int): Char? It returns a character at the given index or returns null if the index
is out of bound from character sequence.

String elements and templates


String elements
The characters which are present in string are known as elements of string. Element of string are accessed by
indexing operation string[index]. String's index value starts from 0 and ends at one less than the size of string
string[string.length-1]. Index 0 represent first element, index 1 represent second element and so on.

1. val str ="Hello, javatpoint"


2. println(str[0]) //prints H
This page by mytechtalk | Kotlin String 52
Example of accessing string element

1. fun main(args: Array<String>) {


2.
3. val str = "Hello, javatpoint!"
4. println(str[0])
5. println(str[1])
6. println(str[str.length-1])
7. }

Output:

H
e
!

String templates
String template expression is a piece of code which is evaluated and its result is returned into string. Both string
types (escaped and raw string) contain template expressions. String templates starts with a dollar sign $ which
consists either a variable name or an arbitrary expression in curly braces.

String template as variable name:

1. val i =10
2. print("i = $i") //i=10
3.
4. fun main(args: Array<String>) {
5. val i =10
6. print("i = $i")//i=10
7. }

Output:

i=10

String template as arbitrary expression in curly braces:

String template is also used in arbitrary expression in curly braces to evaluate a string expression. This is done by
using dollar sign $.

1. fun main(args: Array<String>) {


2. val str = "abc"
3. println("$str is a string which length is ${str.length}")

This page by mytechtalk | Kotlin String 53


4. }
abc is a string which length is 3

String template in raw string:

1. fun main(args: Array<String>) {


2. val a = 10
3. val b = 5
4.
5. val myString = """value $a
6. |is greater than value $b
7. """.trimMargin()
8. println("${myString.trimMargin()}")
9. }

Output:

value 10
is greater than value 5

Kotlin String Literals


Kotlin has two types of string literals:

o Escaped String

o Raw String

Escaped String
Escape String is declared within double quote (" ") and may contain escape characters like '\n', '\t', '\b' ,'\r','\$'etc.

1. val text1 ="Hello, JavaTpoint"


2. //or
3. val text2 ="Hello, JavaTpoint\n"
4. //or
5. val text3 ="Hello, \nJavaTpoint"

Raw String
Row String is declared within triple quote (""" """).It provides facility to declare String in new lines and contain
multiple lines. Row String cannot contain any escape character.

1. val text1 ="""


This page by mytechtalk | Kotlin String 54
2. Welcome
3. To
4. JavaTpoint
5. """

While using raw string with new line, it generates a | as margin prefix. For example:

1. fun main(args: Array<String>) {


2.
3. val text = """Kotlin is official language
4. |announce by Google for
5. |android application development
6. """
7. println(text)
8. }

Output:

Kotlin is official language


|announce by Google for
|android application development

String trimMargin() function


Leading whitespace can be removed with trimMargin() function. By default, trimMargin() function uses | as
margin prefix.

1. fun main(args: Array<String>) {


2.
3. val text = """Kotlin is official language
4. |announce by Google for
5. |android application development
6. """.trimMargin()
7.
8. println(text)
9. }

Output:

Kotlin is official language


announce by Google for
android application development

This page by mytechtalk | Kotlin String 55


However, it can be change by passing a new string inside trimMargin() function.

1. fun main(args: Array<String>) {


2.
3. val text = """Kotlin is official language
4. #announce by Google for
5. #android application development
6. """.trimMargin("#")
7. println(text)
8. }

Output:

Kotlin is official language


announce by Google for
android application development

Kotlin String Equality


In Kotlin, strings equality comparisons are done on the basis of structural equality (==) and referential
equality (===).

In structural equality two objects have separate instances in memory but contain same value.

Referential equality specifies that two different references point the same instance in memory.

Structural equality (==)


To check the two objects containing the same value, we use == operator or != operator for negation. It is
equivalent to equals() in java.

1. fun main(args: Array<String>) {


2. val str1 = "Hello, World!"
3. val str2 = "Hello, World!"
4. println(str1==str2) //true
5. println(str1!=str2) //false
6. }

Output:

true
false

This page by mytechtalk | Kotlin String 56


Referential equality (===)
To check the two different references point to the same instance, we use === operator. The !== operator is used
for negation. a === b specifies true if and only if a and b both point to the same object.

Let's see an example of referential equality to check different reference contains same instance or not. For
creating string we are using a helper method buildString rather than using quotes.

1. fun main(args: Array<String>) {


2. val str1 = buildString { "string value" }
3. val str2 = buildString { "string value" }
4. println(str1===str2)
5. println(str1!==str2)
6. }

Output:

false
true

Kotlin Exception Handling


Exception is a runtime problem which occurs in the program and leads to program termination. This may be
occure due to running out of memory space, array out of bond, condition like divided by zero. To handle this
type of problem during program execution the technique of exception handling is used.

Exception handling is a technique which handles the runtime problems and maintains the flow of program
execution.

In Kotlin, all exception classes are descendants of class Throwable. To throw an exception object, Kotlin uses
the throw expression.

1. throw MyException("this throws an exception")

There are four different keywords used in exception handling. These are:

o try

o catch

o finally

This page by mytechtalk | Kotlin Exception Handling 57


o throw

try: try block contains set of statements which might generate an exception. It must be followed by either catch
or finally or both.

catch: catch block is used to catch the exception thrown from try block.

finally: finally block always execute whether exception is handled or not. So it is used to execute important code
statement.

throw: throw keyword is used to throw an exception explicitly.

Kotlin Unchecked Exception


Unchecked exception is that exception which is thrown due to mistakes in our code. This exception type
extends RuntimeException class. The Unchecked exception is checked at run time. Following are some
example of unchecked exception:

o ArithmeticException: thrown when we divide a number by zero.

o ArrayIndexOutOfBoundExceptions: thrown when an array has been tried to access with incorrect index value.

o SecurityException: thrown by the security manager to indicate a security violation.

o NullPointerException: thrown when invoking a method or property on a null object.

Checked Exception in Java


Checked exception is checked at compile time. This exception type extends the Throwable class.

Following are some example of unchecked exception:

o IOException.

o SQLException etc.

Kotlin try catch


Kotlin try-catch block is used for exception handling in the code. The try block encloses the code which may
throw an exception and the catch block is used to handle the exception. This block must be written within the
method. Kotlin try block must be followed by either catch block or finally block or both.

Syntax of try with catch block


1. try{
2. //code that may throw exception

This page by mytechtalk | Kotlin try catch 58


3. }catch(e: SomeException){
4. //code that handles exception
5. }
Syntax of try with finally block

1. try{
2. //code that may throw exception
3. }finally{
4. // code finally block
5. }

Syntax of try catch with finally block


1. try {
2. // some code
3. }
4. catch (e: SomeException) {
5. // handler
6. }
7. finally {
8. // optional finally block
9. }

Problem without Exception Handling


Lets's see an example which causes exception which is not handled.

1. fun main(args: Array<String>){


2. val data = 20 / 0 //may throw exception
3. println("code below exception ...")
4. }

This above program generates an exception, which causes rest of code below the exception not executable.

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


at ExceptionHandlingKt.main(ExceptionHandling.kt:2)

Solution by exception handling


Let's see the solution of above problem by using try-catch block.

This page by mytechtalk | Kotlin try catch 59


1. fun main(args: Array<String>){
2. try {
3. val data = 20 / 0 //may throw exception
4. } catch (e: ArithmeticException) {
5. println(e)
6. }
7. println("code below exception...")
8. }

Output:

java.lang.ArithmeticException: / by zero
code below exception...

In the above program after implementing try - catch block, rest of code below exception executes.

Kotlin try block as an Expression


We can use try block as an expression which returns a value. The value returned by try expression is either the
last expression of try block or the last expression of catch. Contents of the finally block do not affect the result of
the expression.

Kotlin try as an expression example


Let's see an example of try-catch block as an expression which returns a value. In this example String value to Int
which does not generate any exception and returns last statement of try block.

1. fun main(args: Array<String>){


2. val str = getNumber("10")
3. println(str)
4. }
5. fun getNumber(str: String): Int{
6. return try {
7. Integer.parseInt(str)
8. } catch (e: ArithmeticException) {
9. 0
10. }
11. }

Output:

10

This page by mytechtalk | Kotlin try catch 60


Let's modify the above code which generate an exception and return the last statement of catch block.

1. fun main(args: Array<String>){


2. val str = getNumber("10.5")
3. println(str)
4. }
5. fun getNumber(str: String): Int{
6. return try {
7. Integer.parseInt(str)
8. } catch (e: NumberFormatException) {
9. 0
10. }
11. }

Output:

Kotlin Multiple catch Block


We can use multiple catch block in our code. Kotlin multiple catch blocks are used when we are using different
types of operation in try block which may causes different exceptions in try block.

Kotlin multiple catch block example 1


Let's see an example of multiple catch blocks. In this example we will are performing different types of
operation. These different types of operation may generate different types of exceptions.

1. fun main(args: Array<String>){


2. try {
3. val a = IntArray(5)
4. a[5] = 10 / 0
5. } catch (e: ArithmeticException) {
6. println("arithmetic exception catch")
7. } catch (e: ArrayIndexOutOfBoundsException) {
8. println("array index outofbounds exception")
9. } catch (e: Exception) {
10. println("parent exception class")
11. }
12. println("code after try catch...")
13. }
This page by mytechtalk | Kotlin Multiple catch Block 61
Output:

arithmetic exception catch


code after try catch...

Note: At a time only one exception is occured and at a time only one catch block is executed.

Rule: All catch blocks must be placed from most specific to general i.e. catch for ArithmeticException must
come before catch for Exception.

What happen when we catch from general exception to specific


exception?
It will generate warning. For example:

Let's modify above code and place catch block from general exception to specific exception.

1. fun main(args: Array<String>){


2. try {
3. val a = IntArray(5)
4. a[5] = 10 / 0
5. }
6. catch (e: Exception) {
7. println("parent exception catch")
8. }
9. catch (e: ArithmeticException) {
10. println("arithmetic exception catch")
11. } catch (e: ArrayIndexOutOfBoundsException) {
12. println("array index outofbounds exception")
13. }
14.
15. println("code after try catch...")
16. }

Output at compile time

warning : division by zero


a[5] = 10/0

Output at run time

parent exception catch


code after try catch...
This page by mytechtalk | Kotlin Multiple catch Block 62
Kotlin Nested try-catch block
We can also able to use nested try block whenever required. Nested try catch block is such block in which one
try catch block is implemented into another try block.

The requirement of nested try catch block is arises when a block of code generates an exception and within that
block another code statements also generates another exception.

Syntax of nested try block


1. ..
2. try
3. {
4. // code block
5. try
6. {
7. // code block
8. }
9. catch(e: SomeException)
10. {
11. }
12. }
13. catch(e: SomeException)
14. {
15. }
16. ..

Kotlin nested try block example

1. fun main(args: Array<String>) {


2. val nume = intArrayOf(4, 8, 16, 32, 64, 128, 256, 512)
3. val deno = intArrayOf(2, 0, 4, 4, 0, 8)
4. try {
5. for (i in nume.indices) {
6. try {
7. println(nume[i].toString() + " / " + deno[i] + " is " + nume[i] / deno[i])
8. } catch (exc: ArithmeticException) {
9. println("Can't divided by Zero!")
10. }
11.
This page by mytechtalk | Kotlin Nested try-catch block 63
12. }
13. } catch (exc: ArrayIndexOutOfBoundsException) {
14. println("Element not found.")
15. }
16. }

Output:

4 / 2 is 2
Can't divided by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divided by Zero!
128 / 8 is 16
Element not found

Kotlin finally Block


Kotlin finally block such block which is always executes whether exception is handled or not. So it is used to
execute important code statement.

Kotlin finally Block Example 1


Let's see an example of exception handling in which exception does not occur.

1. fun main (args: Array<String>){


2. try {
3. val data = 10 / 5
4. println(data)
5. } catch (e: NullPointerException) {
6. println(e)
7. } finally {
8. println("finally block always executes")
9. }
10. println("below codes...")
11. }

Output:

2
finally block always executes
below codes...

This page by mytechtalk | Kotlin finally Block 64


Kotlin finally Block Example 2
Let's see an example of exception handling in which exception occurs but not handled.

1. fun main (args: Array<String>){


2. try {
3. val data = 5 / 0
4. println(data)
5. } catch (e: NullPointerException) {
6. println(e)
7. } finally {
8. println("finally block always executes")
9. }
10. println("below codes...")
11. }

Output:

finally block always executes


Exception in thread "main" java.lang.ArithmeticException: / by zero

Kotlin finally Block Example 3


Let's see an example of exception handling in which exception occurs and handled.

1. fun main (args: Array<String>){


2. try {
3. val data = 5 / 0
4. println(data)
5. } catch (e: ArithmeticException) {
6. println(e)
7. } finally {
8. println("finally block always executes")
9. }
10. println("below codes...")
11. }

Output:

java.lang.ArithmeticException: / by zero
finally block always executes
below codes...

This page by mytechtalk | Kotlin finally Block 65


Kotlin throw keyword
Kotlin throw keyword is used to throw an explicit exception. It is used to throw a custom exception.

To throw an exception object we will use the throw-expression.

Syntax of throw keyword


1. throw SomeException()

Kotlin throw example

Let's see an example of throw keyword in which we are validating age limit for driving license.

1. fun main(args: Array<String>) {


2. validate(15)
3. println("code after validation check...")
4. }
5. fun validate(age: Int) {
6. if (age < 18)
7. throw ArithmeticException("under age")
8. else
9. println("eligible for drive")
10. }

Output:

Exception in thread "main" java.lang.ArithmeticException: under age

Kotlin Null Safety


Kotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws
NullPointerException immediately if it found any null argument is passed without executing any other
statements.

Kotlin's type system is aimed to eliminate NullPointerException form the code. NullPointerException can only
possible on following causes:

o An forcefully call to throw NullPointerException();

o An uninitialized of this operator which is available in a constructor passed and used somewhere.

o Use of external java code as Kotlin is Java interoperability.

This page by mytechtalk | Kotlin throw keyword 66


Kotlin Nullable Types and Non-Nullable Types
Kotlin types system differentiates between references which can hold null (nullable reference) and which cannot
hold null (non null reference). Normally,types of String are not nullable. To make string which holds null value,
we have to explicitly define them by putting a ? behind the String as: String?

Nullable Types
Nullable types are declared by putting a ? behind the String as:

1. var str1: String? = "hello"


2. str1 = null // ok

Kotlin example of nullable types

1. fun main(args: Array<String>){


2. var str: String? = "Hello" // variable is declared as nullable
3. str = null
4. print(str)
5. }

Output:

null

Non Nullable Types


Non nullable types are normal strings which are declared as String types as:

1. val str: String = null // compile error


2. str = "hello" // compile error Val cannot be reassign
3. var str2: String = "hello"
4. str2 = null // compile error

What happens when we assign null value to non nullable string?

1. fun main(args: Array<String>){


2. var str: String = "Hello"
3. str = null // compile error
4. print(str)
5. }

Output:

This page by mytechtalk | Kotlin Null Safety 67


It will generate a compile time error.

Error:(3, 11) Kotlin: Null can not be a value of a non-null type String

Checking for null in conditions


Kotlin's If expression is used for checking condition and returns value.

1. fun main(args: Array<String>){


2. var str: String? = "Hello" // variable is declared as nullable
3. var len = if(str!=null) str.length else -1
4. println("str is : $str")
5. println("str length is : $len")
6.
7. str = null
8. println("str is : $str")
9. len = if(str!=null) str.length else -1
10. println("b length is : $len")
11. }

Output:

str is : Hello
str length is : 5
str is : null
b length is : -1

Smart cast
We have seen in previous tutorial Kotlin Nullable Types and Non-Nullable Types how nullable type is
declared. To use this nullable types we have an option to use smart casts. Smart cast is a feature in which Kotlin
compiler tracks conditions inside if expression. If compiler founds a variable is not null of type nullable then the
compiler will allow to access the variable.

For example:
When we try to access a nullable type of String without safe cast it will generate a compile error.

1. var string: String? = "Hello!"


2. print(string.length) // Compile error

To solve the above expression we use a safe cast as:

1. fun main(args: Array<String>){


2. var string: String? = "Hello!"
This page by mytechtalk | Smart cast 68
3. if(string != null) { // smart cast
4. print(string.length) // It works now!
5. }
6. }

Output:

While using is or !is for checking the variable, the compiler tracks this information and internally cast the
variable to target type. This is done inside the scope if is or !is returns true.

Use of is for smart cast


1. fun main(args: Array<String>){
2. val obj: Any = "The variable obj is automatically cast to a String in this scope"
3. if(obj is String) {
4. // No Explicit Casting needed.
5. println("String length is ${obj.length}")
6. }
7. }

Output:

String length is 64

Use of !is for smart cast


1. fun main(args: Array<String>){
2. val obj: Any = "The variable obj is automatically cast to a String in this scope"
3. if(obj !is String) {
4. println("obj is not string")
5.
6. } else
7. // No Explicit Casting needed.
8. println("String length is ${obj.length}")
9. }

Output:

String length is 64

Smart cast work according to the following conditions:

This page by mytechtalk | Smart cast 69


o A val variable always aspect for local properties.

o If a val property is private or internal the check is performed in the same module where the property is declared.

o If the local var variable is not modified between the check and the usage, is not captured in a lambda that modifies
it.

Unsafe and Safe Cast Operator


Unsafe cast operator: as
Sometime it is not possible to cast variable and it throws an exception, this is called as unsafe cast. The unsafe
cast is performed by the infix operator as.

A nullable string (String?) cannot be cast to non nullabe string (String), this throw an exception.

1. fun main(args: Array<String>){


2. val obj: Any? = null
3. val str: String = obj as String
4. println(str)
5. }

The above program throw an exception:

1. Exception in thread "main" kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String
2. at TestKt.main(Test.kt:3)

While try to cast integer value of Any type into string type lead to generate a ClassCastException.

1. val obj: Any = 123


2. val str: String = obj as String
3. // Throws java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

Source and target variable need to nullable for casting to work:

1. fun main(args: Array<String>){


2. val obj: String? = "String unsafe cast"
3. val str: String? = obj as String? // Works
4. println(str)
5. }

Output:

This page by mytechtalk | Unsafe and Safe Cast Operator 70


String unsafe cast

Kotlin Safe cast operator: as?


Kotlin provides a safe cast operator as? for safely cast to a type. It returns a null if casting is not possible rather
than throwing an ClassCastException exception.

Let's see an example, trying to cast Any type of string value which is initially known by programmer not by
compiler into nullable string and nullable int. It cast the value if possible or return null instead of throwing
exception even casting is not possible.

1. fun main(args: Array<String>){


2.
3. val location: Any = "Kotlin"
4. val safeString: String? = location as? String
5. val safeInt: Int? = location as? Int
6. println(safeString)
7. println(safeInt)
8. }

Output:

Kotlin
null

Elvis Operator (?:)


Elvis operator (?:) is used to return the not null value even the conditional expression is null. It is also used to
check the null safety of values.

In some cases, we can declare a variable which can hold a null reference. Suppose that a variable str which
contains null reference, before using str in program we will check it nullability. If variable str found as not null
then its property will use otherwise use some other non-null value.

1. var str: String? = null


2. var str2: String? = "May be declare nullable string"

In above code, the String str contains a null value, before accessing the value of str we need to perform safety
check, whether string contain value or not. In conventional method we perform this safety check using if ...
else statement.

1. var len1: Int = if (str != null) str.length else -1


2. var len2: Int = if (str2 != null) str.length else -1
1. fun main(args: Array<String>){
2.

This page by mytechtalk | Elvis Operator (?:) 71


3. var str: String? = null
4. var str2: String? = "May be declare nullable string"
5. var len1: Int = if (str != null) str.length else -1
6. var len2: Int = if (str2 != null) str2.length else -1
7. println("Length of str is ${len1}")
8. println("Length of str2 is ${len2}")
9. }

Output:

Length of str is -1
Length of str2 is 30

Kotlin provides advance operator known as Elvis operator(?:) which return the not null value even the
conditional expression is null. The above if . . . else operator can be expressed using Elvis operator as bellow:

1. var len1: Int = str?.length ?: -1


2. var len2: Int = str2?.length ?: -1

Elvis operator returns expression left to ?: i.e -1. (str?. length) if it is not null otherwise it returns expression right
to (?:)i.e(-1). The expression right side of Elvis operator evaluated only if the left side returns null.

Kotlin Elvis Operator example


1. fun main(args: Array<String>){
2.
3. var str: String? = null
4. var str2: String? = "May be declare nullable string"
5. var len1: Int = str ?.length ?: -1
6. var len2: Int = str2 ?.length ?: -1
7.
8. println("Length of str is ${len1}")
9. println("Length of str2 is ${len2}")
10. }

Output:

Length of str is -1
Length of str2 is 30

As Kotlin throw and return an expression, they can also be used on the right side of the Elvis operator. This can
be used for checking functional arguments:

1. funfunctionName(node: Node): String? {

This page by mytechtalk | Elvis Operator (?:) 72


2. val parent = node.getParent() ?: return null
3. val name = node.getName() ?: throw IllegalArgumentException("name expected")
4. // ...
5. }

Kotlin Elvis Operatorusing throw and return expression


1. fun main(args: Array<String>){
2. val fruitName: String = fruits()
3. println(fruitName)
4. }
5. fun fruits(): String{
6. val str: String? ="abc"
7. val strLength: Int = if(str!= null) str.length else -1
8. val strLength2: Int = str?.length ?: -1
9. var string = "str = $str\n"+
10. "strLength = $strLength\n"+
11. "strLength2 = $strLength2\n\n"
12.
13. fun check(textOne: String?, textTwo: String?): String?{
14. val textOne = textOne ?: return null
15. val textTwo = textTwo ?: IllegalArgumentException("text exception")
16.
17. return "\ntextOne = $textOne\n"+
18. "textTwo = $textTwo\n"
19. }
20. string += "check(null,\"mango\") = ${check(null,"mango")}\n" +
21. "check(\"apple\",\"orange\") = ${check("apple","orange")}\n"
22. return string
23. }

Output:

str = abc
strLength = 3
strLength2 = 3

check(null,"mango") = null
check("apple","orange") =
textOne = apple
textTwo = orange

This page by mytechtalk | Elvis Operator (?:) 73


Kotlin Array
Array is a collection of similar data either of types Int, String etc. Array in Kotlin has mutable in nature with
fixed size. Which means we can perform both read and writes operations on elements of array.

Syntax of array decleration:


It initializes the element of array of int type with size 5 with all elements as 0 (zero).

1. var myArray = Array<Int>(5){0}

Kotlin array declaration - using arrayOf function


1. var myArray1 = arrayOf(1,10,4,6,15)
2. var myArray2 = arrayOf<Int>(1,10,4,6,15)
3. val myArray3 = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")
4. var myArray4= arrayOf(1,10,4, "Ajay","Prakesh")

Kotlin array declaration - using arrayOf function


1. var myArray5: IntArray = intArrayOf(5,10,20,12,15)

Let's see an example of array in Kotlin. In this example we will see how to initialize and traverse its elements.

Kotlin Array Example 1:


In this example, we are simply initialize an array of size 5 with default value as 0. The index value of array starts
with 0. First element of array is placed at index 0 and last element at one less than the size of array.

1. fun main(args: Array<String>){


2. var myArray = Array<Int>(5){0}
3.
4. for(element in myArray){
5. println(element)
6. }
7. }

Output:

0
0
0
0
0

This page by mytechtalk | Kotlin Array 74


Kotlin Array Example 2:
We can also able to rewrite the value of array using its index value. Since we can able to modify the value of
array, so it is called as mutable in nature. For example:

1. fun main(args: Array<String>){


2. var myArray = Array<Int>(5){0}
3.
4. myArray[1]= 10
5. myArray[3]= 15
6.
7. for(element in myArray){
8. println(element)
9. }
10. }

Output:

0
10
0
15
0

Kotlin Array Example 3 - using arrayOf() and intArrayOf() function:


Array in Kotlin also declare using different functions such as arrayOf(), intArrayOf(), etc. Let's see the example
arrayOf() and intArrayOf() function.

1. fun main(args: Array<String>){


2. val name = arrayOf<String>("Ajay","Prakesh","Michel","John","Sumit")
3. var myArray2 = arrayOf<Int>(1,10,4,6,15)
4. var myArray3 = arrayOf(5,10,20,12,15)
5. var myArray4= arrayOf(1,10,4, "Ajay","Prakesh")
6. var myArray5: IntArray = intArrayOf(5,10,20,12,15)
7.
8. for(element in name){
9. println(element)
10. }
11.
12. println()
13. for(element in myArray2){

This page by mytechtalk | Kotlin Array 75


14. println(element)
15. }
16. println()
17. for(element in myArray3){
18. println(element)
19. }
20. println()
21. for(element in myArray4){
22. println(element)
23. }
24. println()
25. for(element in myArray5){
26. println(element)
27. }
28.
29. }

Output:

Ajay
Prakesh
Michel
John
Sumit

1
10
4
6
15

5
10
20
12
15

1
10
4
Ajay
Prakesh

5
10
15
20
25

This page by mytechtalk | Kotlin Array 76


Kotlin Array Example 4
Suppose that when we try to insert an element at index position greater than array size than what happen? It will
throw an ArrayIndexOutOfBoundException. This is because the index value is not present where we want to
insert the element. Due to this array is called fixed size length. Let's see the example:

1. fun main(args: Array<String>){


2. var myArray5: IntArray = intArrayOf(5,10,20,12,15)
3.
4. myArray5[6]=18 // ArrayIndexOutOfBoundsException
5. for(element in myArray5){
6. println(element)
7. }
8. }

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6


at ArrayListKt.main(Array.kt:4)

Kotlin Array Example 5 - traversing using range:


The Kotlin's array elements are also traverse using index range (minValue..maxValue) or (maxValue..minvalue).
Let's see an example of array traversing using range.

1. fun main(args: Array<String>){


2. var myArray5: IntArray = intArrayOf(5,10,20,12,15)
3.
4. for (index in 0..4){
5. println(myArray5[index])
6. }
7. println()
8. for (index in 0..myArray5.size-1){
9. println(myArray5[index])
10. }
11. }

Output:

5
10
20
12
15

This page by mytechtalk | Kotlin Array 77


5
10
20
12
15

Kotlin Collections
Collections in Kotlin are used to store group of related objects in a single unit. By using collection, we can store,
retrieve manipulate and aggregate data.

Types of Kotlin Collections


Kotlin collections are broadly categories into two different forms. These are:

1. Immutable Collection (or Collection)

2. Mutable Collection

Immutable Collection:
Immutable collection also called Collection supports read only functionalities. Methods of immutable collection
that supports read functionalities are:

Collection Types Methods of Immutable Collection

List listOf()
listOf<T>()

Map mapOf()

Set setOf()

Mutable Collection:
Mutable collections supports both read and write functionalities. Methods of mutable collections that supports
read and write functionalities are:

This page by mytechtalk | Kotlin Collections 78


Collection Types Methods of Mutable Collection

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

Map HashMap
hashMapOf()
mutableMapOf()

Set hashSetOf()
mutableSetOf()

Kotlin List Interface


Kotlin List is an interface and generic collection of elements. The List interface inherits form Collection<T>
class. It is immutable and its methods supports only read functionalities.

To use the List interface we need to use its function called listOf(), listOf<E>().

The elements of list follow the sequence of insertion order and contains index number same as array.

List Interface Declaration


1. public interface List<out E> : Collection<E> (source)

Function of Kotlin List Interface


There are several functions are available in the List interface. Some functions of List interface are mention
below.

Functions Descriptions

abstract fun contains(element: E): It checks specified element is contained in this collection.
Boolean

This page by mytechtalk | Kotlin List Interface 79


abstract fun containsAll(elements: It checks all elements specified are contained in this collection.
Collection<E>): Boolean

abstract operator fun get(index: Int): E It returns the element at given index from the list.

abstract fun indexOf(element: E): Int Returns the index of first occurrence of specified element in the list, or
-1 if specified element is not present in list.

abstract fun isEmpty(): Boolean It returns the true if list is empty, otherwise false.

abstract fun iterator(): Iterator<E> It returns an iterator over the elements of this list.

abstract fun lastIndexOf(element: E): Int It returns the index of last occurrence of specified element in the list, or
return -1 if specified element is not present in list.

abstract fun listIterator(): ListIterator<E> It returns a list iterator over the elements in proper sequence in current
list.

abstract fun listIterator(index: Int): It returns a list iterator over the elements in proper sequence in current
ListIterator<E> list, starting at specified index.

abstract fun subList(fromIndex: Int, It returns a part of list between fromIndex (inclusive) to toIndex
toIndex: Int): List (exclusive).

Kotlin List Example 1


Let's see an example of list using listOf() function.

1. fun main(args: Array<String>){


2. var list = listOf("Ajay","Vijay","Prakash")//read only, fix-size
3. for(element in list){
4. println(element)

This page by mytechtalk | Kotlin List Interface 80


5. }

Output:

Ajay
Vijay
Prakash

Kotlin List Example 2


In the listOf() function we can pass the different types of data at the same time. List can also traverse the list
using index range.

1. fun main(args: Array<String>){


2. var list = listOf(1,2,3,"Ajay","Vijay","Prakash")//read only, fix-size
3. for(element in list){
4. println(element)
5. }
6. println()
7. for(index in 0..list.size-1){
8. println(list[index])
9. }
10. }

Output:

1
2
3
Ajay
Vijay
Prakash

1
2
3
Ajay
Vijay
Prakash

Kotlin List Example 3


For more specific we can provide the generic types of list such as listOf<Int>(), listOf<String>(),
listOf<Any>() Let's see the example.

1. fun main(args: Array<String>){


2. var intList: List<Int> = listOf<Int>(1,2,3)
3. var stringList: List<String> = listOf<String>("Ajay","Vijay","Prakash")
This page by mytechtalk | Kotlin List Interface 81
4. var anyList: List<Any> = listOf<Any>(1,2,3,"Ajay","Vijay","Prakash")
5. println("print int list")
6. for(element in intList){
7. println(element)
8. }
9. println()
10. println("print string list")
11. for(element in stringList){
12. println(element)
13. }
14. println()
15. println("print any list")
16. for(element in anyList){
17. println(element)
18. }
19. }

Output:

print int list


1
2
3

print string list


Ajay
Vijay
Prakash

print any list


1
2
3
Ajay
Vijay
Prakash

Kotlin List Example 4


Let's see the use of different function of Kotlin list interface using listOf<T>() function.

1. fun main(args: Array<String>){


2. var stringList: List<String> = listOf<String>("Ajay","Vijay","Prakash","Vijay","Rohan")
3. var list: List<String> = listOf<String>("Ajay","Vijay","Prakash")
4. for(element in stringList){

This page by mytechtalk | Kotlin List Interface 82


5. print(element+" ")
6. }
7. println()
8. println(stringList.get(0))
9. println(stringList.indexOf("Vijay"))
10. println(stringList.lastIndexOf("Vijay"))
11. println(stringList.size)
12. println(stringList.contains("Prakash"))
13. println(stringList.containsAll(list))
14. println(stringList.subList(2,4))
15. println(stringList.isEmpty())
16. println(stringList.drop(1))
17. println(stringList.dropLast(2))
18. }

Output:

Ajay Vijay Prakash Vijay Rohan


Ajay
1
3
5
true
true
[Prakash, Vijay]
false
[Vijay, Prakash, Vijay, Rohan]
[Ajay, Vijay, Prakash]

The limitation of List interface is that it is immutable. It cannot add more elements in list after its declaration. To
solve this limitation Collection framework provide mutable list.

Kotlin MutableList (mutableListOf())


Kotlin MutableList is an interface and generic collection of elements. MutableList interface is mutable in nature.
It inherits form Collection<T> class. The methods of MutableList interface supports both read and write
functionalities. Once the elements in MutableList have declared, it can be added more elements in it or removed,
so it has no fixed size length.

To use the MutableList interface we use its function called mutableListOf() or mutableListOf<E>().

The elements of MutableList follow the sequence of insertion order and contains index number same as array.

This page by mytechtalk | Kotlin MutableList (mutableListOf()) 83


MutableList Interface Declaration
1. interface MutableList<E> : List<E>, MutableCollection<E> (source)

Function of Kotlin MutableList


There are several methods are available in MutableList interface. Some methods of MutableList interface are
mention below.

Function Descriptions

abstract fun add(element: E): It adds the given element to the collection.
Boolean

abstract fun add(index: Int, It adds the element at specified index.


element: E)

abstract fun addAll(elements: It adds all the elements of given collection to current collection.
Collection<E>): Boolean

abstract fun clear() It removes all the elements from this collection.

abstract fun listIterator(): It returns a list iterator over the elements in proper sequence in current list.
MutableListIterator<E>

abstract fun listIterator(index: It returns a list iterator starting from specified index over the elements in list in
Int): MutableListIterator<E> proper sequence.

abstract fun remove(element: E): It removes the specified element if it present in current collection.
Boolean

abstract fun removeAll(elements: It removes all the elements from the current list which are also present in the
Collection<E>): Boolean specified collection.

This page by mytechtalk | Kotlin MutableList (mutableListOf()) 84


abstract fun removeAt(index: Int): It removes element at given index from the list.
E

abstract fun retainAll(elements: It retains all the elements within the current collection which are present in
Collection<E>): Boolean given collection.

abstract operator fun set(index: It replaces the element and add new at given index with specified element.
Int, element: E): E

abstract fun subList( It returns part of list from specified fromIndex (inclusive) to toIndex
fromIndex: Int, (exclusive) from current list. The returned list is backed by current list, so non-
toIndex: Int structural changes in the returned list are reflected in current list, and vice-
): MutableList<E> versa.

Kotlin MutableList Example 1


Let's see an example of MutableList using mutableListOf() function and traverse its elements.

1. fun main(args: Array<String>){


2. var mutableList = mutableListOf("Ajay","Vijay","Prakash","Vijay")
3.
4. for(element in mutableList){
5. println(element)
6. }
7. println()
8. for(index in 0..mutableList.size-1){
9. println(mutableList[index])
10. }
11. }

Output:

Ajay
Vijay
Prakash
Vijay

Ajay
This page by mytechtalk | Kotlin MutableList (mutableListOf()) 85
Vijay
Prakash
Vijay

Kotlin MutableList Example 2


The function mutableListOf() of MutableList interface provides facilities to add elements after its declaration.
MutableList can also be declared as empty and added elements later but in this situation we need to define its
generic type. For example:

1. fun main(args: Array<String>){


2. var mutableList1 = mutableListOf("Ajay","Vijay")
3. mutableList1.add("Prakash")
4. mutableList1.add("Vijay")
5.
6. var mutableList2 = mutableListOf<String>()
7. mutableList2.add("Ajeet")
8. mutableList2.add("Amit")
9. mutableList2.add("Akash")
10.
11. for(element in mutableList1){
12. println(element)
13. }
14. println()
15. for(element in mutableList2){
16. println(element)
17. }
18. }

Output:

Ajay
Vijay
Prakash
Vijay

Ajeet
Amit
Akash

Kotlin MutableList Example 3


For more specific we can provide the generic types of MutableList interface such as mutableListOf<Int>(),
mutableListOf<String>(), mutableListOf<Any>(). The mutableListOf<Int>() takes only integer

This page by mytechtalk | Kotlin MutableList (mutableListOf()) 86


value, mutableListOf<String>() takes only String value and mutableListOf<Any>() takes different data types
value at the same time. Let's see the example.

1. fun main(args: Array<String>){


2. var mutableListInt: MutableList<Int> = mutableListOf<Int>()
3. var mutableListString: MutableList<String> = mutableListOf<String>()
4. var mutableListAny: MutableList<Any> = mutableListOf<Any>()
5.
6. mutableListInt.add(5)
7. mutableListInt.add(7)
8. mutableListInt.add(10)
9. mutableListInt.add(2,15) //add element 15 at index 2
10.
11. mutableListString.add("Ajeet")
12. mutableListString.add("Ashu")
13. mutableListString.add("Mohan")
14.
15. mutableListAny.add("Sunil")
16. mutableListAny.add(2)
17. mutableListAny.add(5)
18. mutableListAny.add("Raj")
19.
20. println(".....print Int type.....")
21. for(element in mutableListInt){
22. println(element)
23. }
24. println()
25. println(".....print String type.....")
26. for(element in mutableListString){
27. println(element)
28. }
29. println()
30. println(".....print Any type.....")
31. for(element in mutableListAny){
32. println(element)
33. }
34. }

This page by mytechtalk | Kotlin MutableList (mutableListOf()) 87


Output:

.....print Int type.....


5
7
15
10

.....print String type.....


Ajeet
Ashu
Mohan

.....print Any type.....


Sunil
2
5
Raj

Kotlin MutableList Example 4


Let's see the use of different function of MutableList interface using mutableListOf<T>() function.

fun main(args: Array<String>){


var mutableList = mutableListOf<String>()

mutableList.add("Ajay") // index 0
mutableList.add("Vijay") // index 1
mutableList.add("Prakash") // index 2

var mutableList2 = mutableListOf<String>("Rohan","Raj")


var mutableList3 = mutableListOf<String>("Dharmesh","Umesh")
var mutableList4 = mutableListOf<String>("Ajay","Dharmesh","Ashu")

println(".....mutableList.....")
for(element in mutableList){
println(element)
}
println(".....mutableList[2].....")
println(mutableList[2])
mutableList.add(2,"Rohan")
println("......mutableList.add(2,\"Rohan\")......")
for(element in mutableList){
println(element)
}
mutableList.add("Ashu")
println(".....mutableList.add(\"Ashu\")......")
for(element in mutableList){
println(element)
}
mutableList.addAll(1,mutableList3)
println("... mutableList.addAll(1,mutableList3)....")
for(element in mutableList){
println(element)
}
mutableList.addAll(mutableList2)
println("...mutableList.addAll(mutableList2)....")

This page by mytechtalk | Kotlin MutableList (mutableListOf()) 88


for(element in mutableList){
println(element)
}
mutableList.remove("Vijay")
println("...mutableList.remove(\"Vijay\")....")
for(element in mutableList){
println(element)
}
mutableList.removeAt(2)
println("....mutableList.removeAt(2)....")
for(element in mutableList){
println(element)
}
mutableList.removeAll(mutableList2)
println(".... mutableList.removeAll(mutableList2)....")
for(element in mutableList){
println(element)
}

println("....mutableList.set(2,\"Ashok\")....")
mutableList.set(2,"Ashok")
for(element in mutableList){
println(element)
}

println(".... mutableList.retainAll(mutableList4)....")
mutableList.retainAll(mutableList4)
for(element in mutableList){
println(element)
}
println(".... mutableList2.clear()....")
mutableList2.clear()

for(element in mutableList2){
println(element)
}
println(".... mutableList2 after mutableList2.clear()....")
println(mutableList2)

println("....mutableList.subList(1,2)....")
println(mutableList.subList(1,2))

Output:

.....mutableList.....
Ajay
Vijay
Prakash
.....mutableList[2].....
Prakash
......mutableList.add(2,"Rohan")......
Ajay
Vijay
Rohan
Prakash

This page by mytechtalk | Kotlin MutableList (mutableListOf()) 89


.....mutableList.add("Ashu")......
Ajay
Vijay
Rohan
Prakash
Ashu
... mutableList.addAll(1,mutableList3)....
Ajay
Dharmesh
Umesh
Vijay
Rohan
Prakash
Ashu
...mutableList.addAll(mutableList2)....
Ajay
Dharmesh
Umesh
Vijay
Rohan
Prakash
Ashu
Rohan
Raj
...mutableList.remove("Vijay")....
Ajay
Dharmesh
Umesh
Rohan
Prakash
Ashu
Rohan
Raj
....mutableList.removeAt(2)....
Ajay
Dharmesh
Rohan
Prakash
Ashu
Rohan
Raj
.... mutableList.removeAll(mutableList2)....
Ajay
Dharmesh
Prakash
Ashu
....mutableList.set(2,"Ashok")....
Ajay
Dharmesh
Ashok
Ashu
.... mutableList.retainAll(mutableList4)....
Ajay
Dharmesh
Ashu
.... mutableList2.clear()....
.... mutableList2 after mutableList2.clear()....
[]
....mutableList.subList(1,2)....
[Dharmesh]

This page by mytechtalk | Kotlin MutableList (mutableListOf()) 90


Kotlin ArrayList class
Kotlin ArrayList class is used to create a dynamic array. Which means the size of ArrayList class can be
increased or decreased according to requirement. ArrayList class provides both read and write functionalities.

Kotlin ArrayList class follows the sequence of insertion order. ArrayList class is non synchronized and it may
contains duplicate elements. The elements of ArrayList class are accessed randomly as it works on index basis.

Constructor of Kotlin ArrayList


Constructor Description

ArrayList<E>() It is used to create an empty ArrayList

ArrayList(capacity: Int) It is used to create an ArrayList of specified capacity.

ArrayList(elements: Collection<E>) It is used to create an ArrayList filled from the elements of collection.

Functions of Kotlin ArrayList


Function Description

open fun add(element: E): Boolean It is used to add the specific element into the collection.

open fun add(index: Int, element: E) It is used to insert an element at specific index.

open fun addAll(elements: It is used to add all the elements in the specified collection to current
Collection<E>): Boolean collection.

open fun addAll(index: Int, elements: It is used to add all the elements of specified collection into the current
Collection<E>): Boolean list at the specified index.

open fun clear() It is used to removes all elements from the collection.

This page by mytechtalk | Kotlin ArrayList class 91


open fun get(index: Int): E It is used to return the element at specified index in the list.

open fun indexOf(element: E): Int It is used to return the index of first occurrence of specified element in
the list or return -1 if the specified element in not present in the list.

open fun lastIndexOf(element: E): Int It is used to return the last occurrence of given element from the list or
it returns -1 if the given element is not present in the list.

open fun remove(element: E): Boolean It is used to remove a single instance of the specific element from
current collection, if it is available.

open fun removeAt(index: Int): E It is used to remove the specific index element from the list.

open fun removeRange(startIndex: Int, Its remove the range of elements starting from startIndex to endIndex
endIndex: Int) in which endIndex is not includes.

open fun set(index: Int, element: E): E It is used to replaces the element from the specified position from
current list with the specified element.

open fun toArray(): Array<Any?> It is used to return new array of type Array<Any?> with the elements
of this collection.

open fun toString(): String It is used to returns a string representation of the object.

fun trimToSize() It does nothing in this ArrayList implementation.

Kotlin ArrayList Example 1- empty ArrayList


Let's create a simple example of ArrayList class define with empty ArrayList of String and add elements later.

fun main(args: Array<String>){

This page by mytechtalk | Kotlin ArrayList class 92


val arrayList = ArrayList<String>()//Creating an empty arraylist
arrayList.add("Ajay")//Adding object in arraylist
arrayList.add("Vijay")
arrayList.add("Prakash")
arrayList.add("Rohan")
arrayList.add("Vijay")
println(".......print ArrayList.......")
for (i in arrayList) {
println(i)
}
}

Output:

......print ArrayList......
Ajay
Vijay
Prakash
Rohan
Vijay

Kotlin ArrayList Example 2- initialize ArrayList capacity


Let's create an ArrayList class with initialize its initial capacity. The capacity of ArrayList class is not fixed and
it can be change later in program according to requirement.

1. fun main(args: Array<String>){


2.
3. val arrayList1 = ArrayList<String>(5)
4. arrayList1.add("Ajay")//Adding object in arraylist
5. arrayList1.add("Vijay")
6. arrayList1.add("Prakash")
7. arrayList1.add("Rohan")
8. arrayList1.add("Vijay")
9. println(".......print ArrayList1......")
10. for (i in arrayList1) {
11. println(i)
12. }
13. println("size of arrayList1 = "+arrayList1.size)
14. val arrayList2 = ArrayList<Int>(5)
15. arrayList2.add(14)

This page by mytechtalk | Kotlin ArrayList class 93


16. arrayList2.add(20)
17. arrayList2.add(80)
18. println("......print ArrayList2......")
19. for (i in arrayList2) {
20. println(i)
21. }
22. println("size of arrayList2 = "+arrayList2.size)
23. }

Output:

.......print ArrayList1......
Ajay
Vijay
Prakash
Rohan
Vijay
size of arrayList1 = 5
......print ArrayList2......
14
20
80
size of arrayList2 = 3

Kotlin ArrayList Example 3- filled elements in ArrayList using


collection
The elements in Kotlin ArratList class can also be added using other collection. For more specific in ArrayList
class it is declared by its generic types. Elements of ArrayList class also be traverse using iterator() function. For
example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4. var list: MutableList<String> = mutableListOf<String>()
5.
6. list.add("Ajay")
7. list.add("Vijay")
8. list.add("Prakash")
9.
10. arrayList.addAll(list)
11. println("......print ArrayList......")
12. val itr = arrayList.iterator()
13. while(itr.hasNext()) {

This page by mytechtalk | Kotlin ArrayList class 94


14. println(itr.next())
15. }
16. println("size of arrayList = "+arrayList.size)
17. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash
size of arrayList = 3

Kotlin ArrayList Example 4 - get()


The get() function of ArrayList class is used to retrieve the element present at given specified index. For
example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4.
5. arrayList.add("Ajay")
6. arrayList.add("Vijay")
7. arrayList.add("Prakash")
8. arrayList.add("Rohan")
9. arrayList.add("Vijay")
10. println(".......print ArrayList.......")
11. for (i in arrayList) {
12. println(i)
13. }
14. println(".......arrayList.get(2).......")
15. println( arrayList.get(2))
16. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.get(2).......
Prakash

This page by mytechtalk | Kotlin ArrayList class 95


Kotlin ArrayList Example 5 - set()
The set() function of ArrayList class is used to set the given element at specified index and replace if any element
present at specified index. For example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4.
5. arrayList.add("Ajay")
6. arrayList.add("Vijay")
7. arrayList.add("Prakash")
8. arrayList.add("Rohan")
9. arrayList.add("Vijay")
10. println(".......print ArrayList.......")
11. for (i in arrayList) {
12. println(i)
13. }
14. println(".......arrayList.set(2,\"Ashu\").......")
15. arrayList.set(2,"Ashu")
16. println(".......print ArrayList.......")
17. for (i in arrayList) {
18. println(i)
19. }
20. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.set(2,"Ashu").......
.......print ArrayList.......
Ajay
Vijay
Ashu
Rohan
Vijay

This page by mytechtalk | Kotlin ArrayList class 96


Kotlin ArrayList Example 6 - indexOf()
The indexOf() function of ArrayList class is used to retrieve the index value of first occurrence of element or
return -1 if the specified element in not present in the list. For example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4.
5. arrayList.add("Ajay")
6. arrayList.add("Vijay")
7. arrayList.add("Prakash")
8. arrayList.add("Rohan")
9. arrayList.add("Vijay")
10. println(".......print ArrayList.......")
11. for (i in arrayList) {
12. println(i)
13. }
14. println(".......arrayList.indexOf(\"Vijay\").......")
15. println(arrayList.indexOf("Vijay"))
16. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.indexOf("Vijay").......
1

Kotlin ArrayList Example 7 - lastIndexOf()


The lastindexOf() function of ArrayList class is used to retrieve the index value of last occurrence of element or
return -1 if the specified element in not present in the list. For example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4.
5. arrayList.add("Ajay")

This page by mytechtalk | Kotlin ArrayList class 97


6. arrayList.add("Vijay")
7. arrayList.add("Prakash")
8. arrayList.add("Rohan")
9. arrayList.add("Vijay")
10. println(".......print ArrayList.......")
11. for (i in arrayList) {
12. println(i)
13. }
14. println(".......arrayList.lastIndexOf(\"Vijay\").......")
15. println(arrayList.lastIndexOf("Vijay"))
16. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.lastIndexOf("Vijay").......
4

Kotlin ArrayList Example 8 - remove()


The remove () function of ArrayList class is used to remove the first occurrence of element if it is present in the
list. For example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4.
5. arrayList.add("Ajay")
6. arrayList.add("Vijay")
7. arrayList.add("Prakash")
8. arrayList.add("Rohan")
9. arrayList.add("Vijay")
10. println(".......print ArrayList.......")
11. for (i in arrayList) {
12. println(i)
13. }
14. println(".......arrayList.remove(\"Vijay\").......")

This page by mytechtalk | Kotlin ArrayList class 98


15. arrayList.remove("Vijay")
16. for (i in arrayList) {
17. println(i)
18. }
19. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.remove("Vijay").......
Ajay
Prakash
Rohan
Vijay

Kotlin ArrayList Example 9 - removeAt()


The removeAt() function of ArrayList class is used to remove the element of specified index from the list. For
example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4.
5. arrayList.add("Ajay")
6. arrayList.add("Vijay")
7. arrayList.add("Prakash")
8. arrayList.add("Rohan")
9. arrayList.add("Vijay")
10. println(".......print ArrayList.......")
11. for (i in arrayList) {
12. println(i)
13. }
14. println(".......arrayList.remove(3).......")
15. arrayList.removeAt(3)
16. for (i in arrayList) {
17. println(i)
18. }

This page by mytechtalk | Kotlin ArrayList class 99


19. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.remove(3).......
Ajay
Vijay
Prakash
Vijay

Kotlin ArrayList Example 10 - clear()


The clear() function of ArrayList class is used to remove (clear) all the elements of list. For example:

1. fun main(args: Array<String>){


2.
3. val arrayList: ArrayList<String> = ArrayList<String>(5)
4.
5. arrayList.add("Ajay")
6. arrayList.add("Vijay")
7. arrayList.add("Prakash")
8. arrayList.add("Rohan")
9. arrayList.add("Vijay")
10. println(".......print ArrayList.......")
11. for (i in arrayList) {
12. println(i)
13. }
14. println(".......arrayList.clear().......")
15. arrayList.clear()
16.
17. for (i in arrayList) {
18. println(i)
19. }
20. println(".......arrayList.......")
21. println(arrayList)
22. }

Output:
This page by mytechtalk | Kotlin ArrayList class 100
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.clear().......
.......arrayList.......
[]

Kotlin ArrayList: arrayListOf()


An arrayListOf() is a function of ArrayList class. ArrayList is mutable which means it provides both read am
write functionalities. The arrayListOf() function returns an ArrayList type.

Syntax of arrayListOf() function


1. inline fun <T> arrayListOf(): ArrayList<T> (source)
1. fun <T> arrayListOf(vararg elements: T): ArrayList<T> (source)

Function of Kotlin ArrayList


Function Description

open fun add(element: E): Boolean It is used to add the specific element into the collection.

open fun add(index: Int, element: E) It is used to insert an element at specific index.

open fun addAll(elements: It is used to add all the elements in the specified collection to current
Collection<E>): Boolean collection.

open fun addAll(index: Int, elements: It is used to add all the elements of specified collection into the current
Collection<E>): Boolean list at the specified index.

open fun clear() It is used to removes all elements from the collection.

open fun get(index: Int): E It is used to return the element at specified index in the list.

This page by mytechtalk | Kotlin ArrayList: arrayListOf() 101


open fun indexOf(element: E): Int It is used to return the index of first occurrence of specified element in
the list or return -1 if the specified element in not present in the list.

open fun lastIndexOf(element: E): Int It is used to return the last occurrence of given element from the list or
it returns -1 if the given element is not present in the list.

open fun remove(element: E): Boolean It is used to remove a single instance of the specific element from
current collection, if it is available.

open fun removeAt(index: Int): E It is used to remove the specific index element from the list.

open fun removeRange(startIndex: Int, Its remove the range of elements starting from startIndex to endIndex
endIndex: Int) in which endIndex is not includes.

open fun set(index: Int, element: E): E It is used to replaces the element from the specified position from
current list with the specified element.

open fun toArray(): Array<Any?> It is used to return new array of type Array<Any?> with the elements
of this collection.

open fun toString(): String It is used to returns a string representation of the object.

fun trimToSize() It does nothing in this ArrayList implementation.

Kotlin arrayListOf() Example 1


Let's create a simple example of arrayListOf() function.

1. fun main(args: Array<String>){


2. var arrayList = arrayListOf<Int>(4,7,12)
3. for(element in arrayList){
4. println(element)

This page by mytechtalk | Kotlin ArrayList: arrayListOf() 102


5. }
6. }

Output:

4
7
12

Kotlin arrayListOf() Example 2


For more specific we can define the generic types of arrayListOf() function such as arrayListOf<Int>(),
arrqayListOf<String>(),arrayListOf<Any>(). Let's see the example.

1. fun main(args: Array<String>){


2.
3. var intArrayList: ArrayList<Int> = arrayListOf<Int>(1,2,3)
4. var stringArrayList: ArrayList<String> = arrayListOf<String>("Ajay","Vijay","Prakash")
5. var anyArrayList: ArrayList<Any> = arrayListOf<Any>(1,2,3,"Ajay","Vijay","Prakash")
6. println("print int ArrayList")
7. for(element in intArrayList){
8. println(element)
9. }
10. println()
11. println("print string ArrayList")
12. for(element in stringArrayList){
13. println(element)
14. }
15. println()
16. println("print any ArrayList")
17. for(element in anyArrayList){
18. println(element)
19. }
20. }

Output:

print int ArrayList


1
2
3

print string ArrayList


Ajay

This page by mytechtalk | Kotlin ArrayList: arrayListOf() 103


Vijay
Prakash

print any ArrayList


1
2
3
Ajay
Vijay
Prakash

Kotlin arrayListOf() Example 3- iterator() function


The elements of ArrayList class is also be traverse using inbuilt iterator() function. For example:

1. fun main(args: Array<String>){


2. val list: ArrayList<String> = arrayListOf<String>()
3.
4. list.add("Ajay")
5. list.add("Vijay")
6. list.add("Prakash")
7.
8. println(".......print ArrayList.......")
9. val itr = list.iterator()
10. while(itr.hasNext()) {
11. println(itr.next())
12. }
13. }

Output:

.......print ArrayList.......
Ajay
Vijay
Prakash

Kotlin arrayListOf() Example 4 - get()


The get() function of arrayListOf() is used to retrieve the element present at specified index. For example:

1. fun main(args: Array<String>){


2.
3. val list: ArrayList<String> = arrayListOf<String>()
4.
5. list.add("Ajay")

This page by mytechtalk | Kotlin ArrayList: arrayListOf() 104


6. list.add("Vijay")
7. list.add("Prakash")
8. list.add("Rohan")
9. list.add("Vijay")
10. println(".......print list.......")
11. for (i in list) {
12. println(i)
13. }
14. println(".......list.get(2).......")
15. println( list.get(2))
16. }

Output:

.......print list.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......list.get(2).......
Prakash

Kotlin arrayListOf() Example 5 - set()


The set() function of arrayListOf() is used to set the given element at specified index and replace if any element
already present at that index. For example:

1. fun main(args: Array<String>){


2.
3. val list: ArrayList<String> = arrayListOf<String>()
4.
5. list.add("Ajay")
6. list.add("Vijay")
7. list.add("Prakash")
8.
9. println(".......print list.......")
10. for (i in list) {
11. println(i)
12. }
13. println(".......arrayList.set(2,\"Rohan\").......")
14. list.set(2,"Rohan")

This page by mytechtalk | Kotlin ArrayList: arrayListOf() 105


15. println(".......print ArrayList.......")
16. for (i in list) {
17. println(i)
18. }
19. }

Output:

.......print list.......
Ajay
Vijay
Prakash
.......list.set(2,"Rohan").......
.......print list.......
Ajay
Vijay
Rohan

Kotlin arrayListOf() Example - add and print Employee data


Let's create an another example of arrayListOf() function of ArrayList class. In this example we are adding and
traversing Employee class data. Here Employee class is bean class which defines the property of Employee.

1. class Employee(var id: Int, var name: String, var phone: Int, var city: String)
1. fun main(args: Array<String>){
2. val arrayList: ArrayList<Employee> = arrayListOf<Employee>()
3. val e1 = Employee(101, "Ajay", 55555, "Delhi")
4. val e2 = Employee(102, "Rahul", 44443, "Mumbai")
5. val e3 = Employee(103, "Sanjay", 45422, "Noida")
6. arrayList.add(e1)
7. arrayList.add(e2)
8. arrayList.add(e3)
9.
10. for (e in arrayList) {
11. println("${e.id} ${e.name} ${e.phone} ${e.city}")
12. }
13. }

Output:

101 Ajay 55555 Delhi


102 Rahul 44443 Mumbai
103 Sanjay 45422 Noida

Kotlin Map Interface


This page by mytechtalk | Kotlin Map Interface 106
Kotlin Map is an interface and generic collection of elements. Map interface holds data in the form of key and
value pair. Map key are unique and holds only one value for each key. The key and value may be of different
pairs such as <Int, Int>,<Int, String>, <Char, String>etc. This interface is immutable, fixed size and its methods
support read only access.

To use the Map interface we need to use its function called mapOf() or mapOf<k,v>().

Map Interface Declaration


1. interface Map<K, out V> (source)

Properties of Map Interface


Properties Description

abstract val entries: It returns only read all key and value pair of Set Interface in current map.
Set<Entry<K, V>>

abstract val keys: Set<K> It returns only read all key of Set Interface in current map.

abstract val keys: Set<K> It returns the number of key and value pair in current map.

abstract val values: It returns only read Collection of all valued in current map. This collection may
Collection<V> contain duplicate values.

Functions of Map Interface


There are several functions are available in Map interface. Some functions of Map interface are mention below.

Functions Description

fun <K, V> Map<key, value>.getValue(key: It returns a value of given key or throws an exception if no such key
K): V is available in the map.

operator fun <V, V1 : V> Map<in String, It returns the value of the property for the given object from current
V>.getValue(

This page by mytechtalk | Kotlin Map Interface 107


thisRef: Any?, read- only map.
property: KProperty<*>
): V1

operator fun <K, V> Map<out K, It checks is the given key contains in map.
V>.contains(key: K): Boolean

fun <K> Map<out K, *>.containsKey(key: If map contains the specified key it returns true.
K): Boolean

fun <K, V> Map<K, If map maps one or more keys to specified value it returns true.
V>.containsValue(value: V): Boolean

fun <K, V> Map<out K, V>.getOrDefault( It returns the value which is given by key in mapped, or returns
key: K, default value if map dose not contains mapping for the given key.
defaultValue: V
): V

fun <K, V> Map<out K, V>.asIterable(): It creates an instance of Iterable interface which wraps the original
Iterable<Entry<K, V>> map returning its entries when being iterated.

fun <K, V> Map<out K, V>.asIterable(): It creates an instance of Iterable interface which wraps the original
Iterable<Entry<K, V>> map returning its entries when being iterated.

fun <K, V> Map<out K, V>.asSequence(): It creates a Sequence interface instance which wraps the current
Sequence<Entry<K, V>> map and returning its entries when it has iterated.

operator fun <K, V> Map<out K, It returns an Iterator over the entries in the Map.
V>.iterator(): Iterator<Entry<K, V>>

This page by mytechtalk | Kotlin Map Interface 108


operator fun Map.minus(key: K): Map It returns a map which contains all the entries of original map
except the entry of mention key.

operator fun <K, V> Map<out K, V>.minus( It returns a map which contains all the entries of original map
keys: Iterable<K> except those entries key which are contained in the mention key
): Map<K, V> collection.

operator fun <K, V> Map<out K, V>.minus( It returns a map which contains all the entries of original map
keys: Sequence<K> except those entries key which are contained in the given key
): Map<K, V> sequence.

operator fun <K, V> Map<out K, V>.plus( It creates a new read only map by adding or replacing an entry to
pair: Pair<K, V> current map from a given key-value pair.
): Map<K, V>

operator fun <K, V> Map<out K, V>.plus( It creates a new read only map by adding or replacing entries to
pairs: Iterable<Pair<K, V>> current map from a given collection of key-value pairs.
): Map<K, V>

operator fun <K, V> Map<out K, V>.plus( It creates a new read only map by adding or replacing entries to
pairs: Sequence<Pair<K, V>> current map from a given sequence of key-value pairs.
): Map<K, V>

Kotlin Map Interface Example 1


Let's create an example of declaring and traversing the value of map using mapOf<k,v>() function. In this
example, we create key of Int and value of String types.

1. fun main(args: Array<String>){


2.
3. val myMap = mapOf<Int,String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4. for(key in myMap.keys){
5. println(myMap[key])

This page by mytechtalk | Kotlin Map Interface 109


6. }
7. }

Output:

Ajay
Vijay
Prakash

Kotlin Map Interface Example 2 - generic


For more specific we can provide generic type Map such as myMap: Map<k, v> = mapOf<k,v>().

1. fun main(args: Array<String>){


2.
3. val myMap: Map<Int, String> = mapOf<Int,String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4. for(key in myMap.keys){
5. println("Element at key $key = ${myMap.get(key)}")
6. }
7. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash

Kotlin Map Interface Example 3 - non generic


If we cannot specify any types of key and value of Map Interface then it can take different types of key and
value. This is because all class internally uses <Any, Any> types. For example:

1. fun main(args: Array<String>){


2.
3. val myMap = mapOf(1 to "Ajay", 4 to "Vijay", 3 to "Prakash","ram" to "Ram", "two" to 2)
4. for(key in myMap.keys){
5. println("Element at key $key = ${myMap.get(key)}")
6. }
7. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
Element at key ram = Ram

This page by mytechtalk | Kotlin Map Interface 110


Element at key two = 2

Kotlin Map Interface Example 4 - mapOf().getValue()


1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8. println(".....myMap.getValue(4).......")
9. println(myMap.getValue(4))
10. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
.....myMap.getValue(4).......
Vijay

Kotlin Map Interface Example 5 - mapOf().contains()


1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8.
9. println(".....myMap.contains(3).......")
10. println( myMap.contains(3))
11. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
.....myMap.contains(3).......
true

This page by mytechtalk | Kotlin Map Interface 111


Kotlin Map Interface Example 6 - mapOf().containsKey()
1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8.
9. println("......myMap.containsKey(2)......")
10. println(myMap.containsKey(2))
11. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
......myMap.containsKey(2)......
false

Kotlin Map Interface Example 7 - mapOf().containsValue ()


1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8. println("......myMap.containsValue(\"Ajay\")......")
9. println(myMap.containsValue("Ajay"))
10. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
......myMap.containsValue("Ajay")......
true

Kotlin Map Interface Example 8 - mapOf().get()


1. fun main(args: Array<String>){
This page by mytechtalk | Kotlin Map Interface 112
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8. println(".....myMap.get(1).......")
9. println(myMap.get(1))
10. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
.....myMap.get(1).......
Ajay

Kotlin Map Interface Example 9 - mapOf().getOrDefault ()


1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8.
9. println("......myMap.getOrDefault(3, \"Vijay\")......")
10. println(myMap.getOrDefault(3, "Vijay"))
11. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
......myMap.getOrDefault(3, "Vijay")......
Prakash

Kotlin Map Interface Example 10 - mapOf().asIterable ()


1. fun main(args: Array<String>){
2.

This page by mytechtalk | Kotlin Map Interface 113


3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8. println(".......myMap.asIterable().....")
9. for(itr in myMap.asIterable()){
10. println("key = ${itr.key} value = ${itr.value}")
11. }
12. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
.......myMap.asIterable().....
key = 1 value = Ajay
key = 4 value = Vijay
key = 3 value = Prakash

Kotlin Map Interface Example 11 - mapOf().iterator()


1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8. println("......myMap.iterator()......")
9. for(itr1 in myMap.iterator()){
10. println("key = ${itr1.key} value = ${itr1.value}")
11. }
12. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
......myMap.iterator()......
key = 1 value = Ajay
key = 4 value = Vijay
key = 3 value = Prakash

This page by mytechtalk | Kotlin Map Interface 114


Kotlin Map Interface Example 12 - mapOf().minus()
1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8. println("......myMap.minus(4)......")
9. for(m in myMap.minus(4)){
10. println(myMap[m.key])
11. }
12. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
Element at key 3 = Prakash
......myMap.minus(4)......
Ajay
Prakash

Kotlin Map Interface Example 13 - mapOf().plus()


1. fun main(args: Array<String>){
2.
3. val myMap: Map<Int,String> = mapOf<Int, String>(1 to "Ajay", 4 to "Vijay", 3 to "Prakash")
4.
5. for(key in myMap.keys){
6. println("Element at key $key = ${myMap.get(key)}")
7. }
8. println("......myMap.plus(Pair(5, \"Rohan\"))......")
9. for(p in myMap.plus(Pair(5, "Rohan"))){
10. println("Element at key ${p.key} = ${p.value}")
11. }
12.
13. }

Output:

Element at key 1 = Ajay


Element at key 4 = Vijay
This page by mytechtalk | Kotlin Map Interface 115
Element at key 3 = Prakash
......myMap.plus(Pair(5, "Rohan"))......
Element at key 1 = Ajay
Element at key 4 = Vijay
Element at key 3 = Prakash
Element at key 5 = Rohan

Kotlin HashMap class


Kotlin HashMap is class of collection based on MutableMap interface. Kotlin HashMap class implements the
MutableMap interface using Hash table. It store the data in the form of key and value pair. It is represented as
HashMap<key, value> or HashMap<K, V>.

The implementation of HashMap class does not make guarantees about the order of data of key, value and entries
of collections.

Constructor of Kotlin HashMap class


Constructor Description

HashMap() It constructs an empty HashMap instance

HashMap(initialCapacity: Int, loadFactor: It is used to constructs a HashMap of specified capacity.


Float = 0f)

HashMap(original: Map<out K, V>) It constructs a HashMap instance filled with contents of specified
original map.

Functions of Kotlin HashMap class


Functions Description

open fun put(key: K, value: V): V? It puts the specified key and value in the map

open operator fun get(key: K): V? It returns the value of specified key, or null if no such specified key is
available in map.

This page by mytechtalk | Kotlin HashMap class 116


open fun containsKey(key: K): It returns true if map contains specifies key.
Boolean

open fun containsValue(value: V): It returns true if map maps one of more keys to specified value.
Boolean

open fun clear() It removes all elements from map.

open fun remove(key: K): V? It removes the specified key and its corresponding value from map

Kotlin HashMap Example 1- empty HashMap


Let's create a simple example of HashMap class define with empty HashMap of <Int, String> and add elements
later. To print the value of HashMap we will either use HashMap[key] or HashMap.get(key).

1. fun main(args: Array<String>){


2.
3. val hashMap:HashMap<Int,String> = HashMap<Int,String>() //define empty hashmap
4. hashMap.put(1,"Ajay")
5. hashMap.put(3,"Vijay")
6. hashMap.put(4,"Praveen")
7. hashMap.put(2,"Ajay")
8. println(".....traversing hashmap.......")
9. for(key in hashMap.keys){
10. println("Element at key $key = ${hashMap[key]}")
11. }}

Output:

.....traversing hashmap.......
Element at key 1 = Ajay
Element at key 2 = Ajay
Element at key 3 = Vijay
Element at key 4 = Praveen

Kotlin HashMap Example 2- HashMap initial capacity


HashMap can also be initialize with its initial capacity. The capacity can be changed by adding and replacing its
element.

This page by mytechtalk | Kotlin HashMap class 117


1. fun main(args: Array<String>){
2.
3. val hashMap:HashMap<String,String> = HashMap<String,String>(3)
4. hashMap.put("name","Ajay")
5. hashMap.put("city","Delhi")
6. hashMap.put("department","Software Development")
7. println(".....traversing hashmap.......")
8. for(key in hashMap.keys){
9. println("Element at key $key = ${hashMap[key]}")
10. }
11. println(".....hashMap.size.......")
12. println(hashMap.size)
13. hashMap.put("hobby","Travelling")
14. println(".....hashMap.size after adding hobby.......")
15. println(hashMap.size)
16. println(".....traversing hashmap.......")
17. for(key in hashMap.keys){
18. println("Element at key $key = ${hashMap.get(key)}")
19. }
20. }

Output:

.....traversing hashmap.......
Element at key name = Ajay
Element at key department = Software Development
Element at key city = Delhi
.....hashMap.size.......
3
.....hashMap.size after adding hobby.......
4
.....traversing hashmap.......
Element at key name = Ajay
Element at key department = Software Development
Element at key city = Delhi
Element at key hobby = Travelling

Kotlin HashMap Example 3- remove() and put()


The function remove() is used to replace the existing value at specified key with specified value.
The put() function add a new value at specified key and replace the old value. If put() function does not found
any specified key, it put a new value at specified key.

1. fun main(args: Array<String>){

This page by mytechtalk | Kotlin HashMap class 118


2.
3. val hashMap:HashMap<Int,String> = HashMap<Int,String>()
4. hashMap.put(1,"Ajay")
5. hashMap.put(3,"Vijay")
6. hashMap.put(4,"Prakash")
7. hashMap.put(2,"Rohan")
8.
9. println(".....traversing hashmap.......")
10. for(key in hashMap.keys){
11. println("Element at key $key = ${hashMap[key]}")
12. }
13.
14. hashMap.replace(3,"Ashu")
15. hashMap.put(2,"Raj")
16. println(".....hashMap.replace(3,\"Ashu\")... hashMap.replace(2,\"Raj\").......")....")
17. for(key in hashMap.keys){
18. println("Element at key $key = ${hashMap[key]}")
19. }
20. }

Output:

.....traversing hashmap.......
Element at key 1 = Ajay
Element at key 2 = Rohan
Element at key 3 = Vijay
Element at key 4 = Prakash
.....hashMap.replace(3,"Ashu")...hashMap.put(2,"Raj")....
Element at key 1 = Ajay
Element at key 2 = Raj
Element at key 3 = Ashu
Element at key 4 = Prakash

Kotlin HashMap Example 4 - containsKey(key) and


containsValue(value)
The Function containsKey() returns true if the specified key is present in HashMap or returns false if no such key
exist.

The Function containsValue() is used to check whether the specified value is exist in HashMap or not. If value
exists in HashMap, it will returns true else returns false.

1. fun main(args: Array<String>){


2.
This page by mytechtalk | Kotlin HashMap class 119
3. val hashMap:HashMap<Int,String> = HashMap<Int,String>()
4. hashMap.put(1,"Ajay")
5. hashMap.put(3,"Vijay")
6. hashMap.put(4,"Prakash")
7. hashMap.put(2,"Rohan")
8.
9. println(".....traversing hashmap.......")
10. for(key in hashMap.keys){
11. println("Element at key $key = ${hashMap[key]}")
12. }
13.
14.
15. println(".....hashMap.containsKey(3).......")
16. println(hashMap.containsKey(3))
17. println(".....hashMap.containsValue(\"Rohan\").......")
18. println(hashMap.containsValue("Rohan"))
19. }

Output:

.....traversing hashmap.......
Element at key 1 = Ajay
Element at key 2 = Rohan
Element at key 3 = Vijay
Element at key 4 = Prakash
.....hashMap.containsKey(3).......
true
.....hashMap.containsValue("Rohan").......
true

Kotlin HashMap Example 5 - clear()


The clear() function is used to clear all the data from the HashMap.

1. fun main(args: Array<String>){


2.
3. val hashMap:HashMap<Int,String> = HashMap<Int,String>()
4. hashMap.put(1,"Ajay")
5. hashMap.put(3,"Vijay")
6. hashMap.put(4,"Prakash")
7. hashMap.put(2,"Rohan")
8.

This page by mytechtalk | Kotlin HashMap class 120


9. println(".....traversing hashmap.......")
10. for(key in hashMap.keys){
11. println("Element at key $key = ${hashMap[key]}")
12. }
13.
14.
15. println(".....hashMap.clear().......")
16. hashMap.clear()
17. println(".....print hashMap after clear().......")
18. println(hashMap)
19. }

Output:

.....traversing hashmap.......
Element at key 1 = Ajay
Element at key 2 = Rohan
Element at key 3 = Vijay
Element at key 4 = Prakash
.....hashMap.clear().......
.....print hashMap after clear().......
{}

Kotlin HashMap: hashMapOf()


A hashMapOf() is a function of HashMap class. It returns a new HashMap with the specified contents. It
contains pairs of data in the form of key and value. HashMap is mutable collection which provides both read am
write functionalities.

Syntax of hashMapOf() function


1. inline fun <K, V> hashMapOf(): HashMap<K, V> (source)
1. fun <K, V> hashMapOf(vararg pairs: Pair<K, V>): HashMap<K, V> (source)

Functions of Kotlin HashMap class


Function Description

open fun put(key: K, value: V): V? It puts the specified key and value in the map

open operator fun get(key: K): V? It returns the value of specified key, or null if no such specified key is

This page by mytechtalk | Kotlin HashMap: hashMapOf() 121


available in map.

open fun containsKey(key: K): It returns true if map contains specifies key.
Boolean

open fun containsValue(value: V): It returns true if map maps one of more keys to specified value.
Boolean

open fun clear() It removes all elements from map.

open fun remove(key: K): V? It removes the specified key and its corresponding value from map

Kotlin hashMapOf() Example 1


The hashMapOf() function of HashMap can be declared as different generic types such as hashMapOf<Int,
String>(), hashMapOf<String, String>(), hashMapOf<Any, Any>() etc.

1. fun main(args: Array<String>){


2.
3. val intMap: HashMap<Int, String> = hashMapOf<Int,String>(1 to "Ashu",4 to "Rohan", 2 to "Ajeet", 3 to "Vijay")
4.
5. val stringMap: HashMap<String,String> = hashMapOf<String,String>("name" to "Ashu")
6. stringMap.put("city", "Delhi")
7. stringMap.put("department", "Development")
8. stringMap.put("hobby", "Playing")
9. val anyMap: HashMap<Any, Any> = hashMapOf<Any, Any>(1 to "Ashu", "name" to "Rohsan", 2 to 200)
10. println(".....traverse intMap........")
11. for(key in intMap.keys){
12. println(intMap[key])
13. }
14. println("......traverse stringMap.......")
15. for(key in stringMap.keys){
16. println(stringMap[key])
17. }

This page by mytechtalk | Kotlin HashMap: hashMapOf() 122


18. println("......traverse anyMap.......")
19. for(key in anyMap.keys){
20. println(anyMap[key])
21. }
22. }

Output:

.....traverse intMap........
Ashu
Ajeet
Vijay
Rohan
......traverse stringMap.......
Ashu
Development
Delhi
Playing
......traverse anyMap.......
Rohsan
Ashu
200

Kotlin hashMapOf() Example 2 - containsKey()


The containsKey() function returns true if it contains the mention key in the HashMap, otherwise it returns false.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println("......stringMap.containsKey(\"name\").......")
15. println(stringMap.containsKey("name"))
16. }

Output:
This page by mytechtalk | Kotlin HashMap: hashMapOf() 123
......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.containsKey("name").......
true

Kotlin hashMapOf() Example 3 - containsValue()


The containsValue() function returns true if it contains the mention value in the HashMap, otherwise it returns
false.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println(".......stringMap.containsValue(\"Delhi\")......")
15. println(stringMap.containsValue("Delhi"))
16. println(stringMap.containsValue("Mumbai"))
17. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
.......stringMap.containsValue("Delhi")......
true
false

Kotlin hashMapOf() Example 4 - contains()


The contains() function returns true if it contains the mention key in the HashMap, otherwise it returns false.

This page by mytechtalk | Kotlin HashMap: hashMapOf() 124


1. fun main(args: Array<String>){
2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println("......stringMap.contains(\"city\").......")
15. println(stringMap.contains("city"))
16. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.contains("city").......
true

Kotlin hashMapOf() Example 5 - replace(key, value)


The replace(key, value) function is used to replace the existing value at specified key with new specified value.
The replace(key, value) function returns the replaced value.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
This page by mytechtalk | Kotlin HashMap: hashMapOf() 125
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println("......stringMap.replace(\"city\",\"Mumbai\").......")
15. println(stringMap.replace("city","Mumbai"))
16. println("......traverse stringMap after stringMap.replace(\"city\",\"Mumbai\").......")
17. for(key in stringMap.keys){
18. println("Key = ${key} , value = ${stringMap[key]}")
19. }
20. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.replace("city","Mumbai").......
Delhi
......traverse stringMap after stringMap.replace("city","Mumbai").......
Key = city , value = Mumbai
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing

Kotlin hashMapOf() Example 6 - replace(key, oldValue, newValue)


The replace(key, oldValue, newValue) function is used to replace the existing old value at specified key with
new specified value. The replace(key, newValue, oldValue) function returns true if it replace old value with new
else it returns false.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }

This page by mytechtalk | Kotlin HashMap: hashMapOf() 126


13.
14. println(".......stringMap.replace(\"department\", \"Development\",\"Management\")......")
15. println(stringMap.replace("department", "Development","Management"))
16. println("......traverse stringMap after stringMap.replace(\"department\", \"Development\",\"Management\").......")
17. for(key in stringMap.keys){
18. println("Key = ${key} , value = ${stringMap[key]}")
19. }
20. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
.......stringMap.replace("department", "Development","Management")......
true
......traverse stringMap after stringMap.replace("department", "Development","Management").......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Management
Key = hobby , value = Playing

Kotlin hashMapOf() Example 7 - hashMapOf().size,


hashMapOf().key
The size property of hashMapOf() function returns total size of HashMap and the key property returns all keys of
HashMap.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println(".....stringMap.size........")
This page by mytechtalk | Kotlin HashMap: hashMapOf() 127
15. println(stringMap.size)
16.
17. println(".......stringMap.keys......")
18. println(stringMap.keys)
19. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
.....stringMap.size........
4
.......stringMap.keys......
[city, name, department, hobby]

Kotlin hashMapOf() Example 8 - getValue(key), getOrDefault(key,


defaultValue)
The getValue() function returns value of specified key of the HashMap. Whereas getOrDefault() function returns
corresponding value of specified key if it exist in the HashMap or it returns mentioned default value if no such
key exists in HashMap.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println(".......stringMap.getValue(\"department\")......")
15. println(stringMap.getValue("department"))
16.
17. println(".......stringMap.getOrDefault(\"name\", \"Default Value\")......")
18. println(stringMap.getOrDefault("name", "Default Value"))
This page by mytechtalk | Kotlin HashMap: hashMapOf() 128
19. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
.......stringMap.getValue("department")......
Development
.......stringMap.getOrDefault("name", "Default Value")......
Ashu

Kotlin hashMapOf() Example 9 - remove(key)


The remove(key) function is used to remove the specified key along with its corresponding value. The
remove(key) function returns the removed value.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println("......stringMap.remove(\"city\").......")
15. println(stringMap.remove("city"))
16. println("......traverse stringMap after stringMap.remove(\"city\").......")
17. for(key in stringMap.keys){
18. println("Key = ${key} , value = ${stringMap[key]}")
19. }
20. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
This page by mytechtalk | Kotlin HashMap: hashMapOf() 129
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.remove("city").......
Delhi
......traverse stringMap after stringMap.remove("city").......
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing

Kotlin hashMapOf() Example 10 - remove(key, value)


The remove(key, value) function is used to remove the specified key along with its corresponding value. The
remove(key, value) function returns true if it remove the specified key along with its value else it returns false.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13. println(".......stringMap.remove(\"hobby\",\"Playing\")......")
14. println(stringMap.remove("hobby","Playing"))
15. println("......traverse stringMap after stringMap.remove(\"hobby\",\"Playing\").......")
16. for(key in stringMap.keys){
17. println("Key = ${key} , value = ${stringMap[key]}")
18. }
19. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
.......stringMap.remove("hobby","Playing")......
true
......traverse stringMap after stringMap.remove("hobby","Playing").......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
This page by mytechtalk | Kotlin HashMap: hashMapOf() 130
Kotlin hashMapOf() Example 11 - set(key, value)
The set(key, value) function is used to set the given value at specified key if it exist. If the key does not exist in
the HashMap it will add new key and set the given value corresponding to it.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. stringMap.set("name","Ashutosh")
15. stringMap.set("skill","Kotlin")
16. println("......traverse stringMap after stringMap.set(\"name\",\"Ashutosh\") and stringMap.set(\"skill\",\"Kotlin\").......")

17. for(key in stringMap.keys){


18. println("Key = ${key} , value = ${stringMap[key]}")
19. }
20. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.set("name","Ashutosh").......
......traverse stringMap after stringMap.set("name","Ashutosh") and stringMap.set("skill","Kotlin").......
Key = city , value = Delhi
Key = skill , value = Kotlin
Key = name , value = Ashutosh
Key = department , value = Development
Key = hobby , value = Playing

This page by mytechtalk | Kotlin HashMap: hashMapOf() 131


Kotlin hashMapOf() Example 12 - clear()
The clear() function is used to clear (or remove) all the key, value pair from the HashMap.

1. fun main(args: Array<String>){


2.
3. val stringMap: HashMap<String,String> = hashMapOf<String,String>()
4. stringMap.put("name", "Ashu")
5. stringMap.put("city", "Delhi")
6. stringMap.put("department", "Development")
7. stringMap.put("hobby", "Playing")
8.
9. println("......traverse stringMap.......")
10. for(key in stringMap.keys){
11. println("Key = ${key} , value = ${stringMap[key]}")
12. }
13.
14. println("......stringMap.clear().......")
15. println(stringMap.clear())
16. println(stringMap)
17.
18. }

Output:

......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.clear().......
kotlin.Unit
{}

Kotlin MutableMap Interface


Kotlin MutableMap is an interface of collection framework that holds the object in the form of key and value
pair. The values of MutableMap interface are retrieved by using their corresponding keys. The key and value
may be of different pairs such as <Int, Int>,<Int, String>, <Char, String> etc. Each key of MutableMap holds
only one value.

To use the MutableMap interface we need to use its function called mutableMapOf() or mutableMapOf
<k,v>().

This page by mytechtalk | Kotlin MutableMap Interface 132


Kotlin MutableMap Interface Declaration
1. interface MutableMap<K, V> : Map<K, V> (source)

Properties of MutableMap
Properties Description

abstract val entries: This returns a MutableSet of all its key and value pairs in the map.
MutableSet<MutableEntry<K, V>>

abstract val keys: MutableSet<K> This returns all the keys of MutableSet in this map.

abstract val values: MutableCollection<V> This returns all the values of MutableCollection in the current map.
This collection may contain duplicate values.

Function of Kotlin MutableMap


Function Description

abstract fun put(key: K, value: V): V? It adds the given value with the specified key in the map.

abstract fun putAll(from: Map<out K, V>) This updates the current map with key/value pairs from the
mentioned map.

abstract fun remove(key: K): V? It removes the specified key with its corresponding value from the
map.

open fun remove(key: K, value: V): It removes the key and value entities from the map only if it exist in
Boolean the map.

abstract fun clear() This function is used to removes all the elements from the map.

This page by mytechtalk | Kotlin MutableMap Interface 133


operator fun <K, V> Map<out K, It checks the given key in the map.
V>.contains(key: K): Boolean

abstract fun containsKey(key: K): Boolean It returns the true if map contains the specified key.

fun <K> Map<out K, *>.containsKey(key: It returns the true if map contains the specified key.
K): Boolean

abstract fun containsValue(value: V): It returns true if the map maps one or more keys for the given value.
Boolean

fun <K, V> Map<K, It returns true if the map maps one or more keys for the given value.
V>.containsValue(value: V): Boolean

fun <K, V> Map<out K, V>.count(): Int It returns the total number of entities of the map

operator fun <K, V> Map<out K, It returns the value corresponding to mention key, or null if no such
V>.get(key: K): V? key found in the map.

fun <K, V> Map<out K, V>.getOrDefault( It returns the value with corresponding mention key, or it returns
key: K, default value if no such mapping for the key in the map.
defaultValue: V
): V

fun <K, V> Map<K, V>.getOrElse( It returns the value for the mention key in the map, or it returns the
key: K, default value function if no such entry found for the given key.
defaultValue: () -> V
): V

fun <K, V> Map<K, V>.getValue(key: K): It returns the value corresponding to given key, or it throws an

This page by mytechtalk | Kotlin MutableMap Interface 134


V exception if no key found in the map.

Kotlin MutableMap Example - 1 traversing MutableMap


Let's create an example to create a MutableMap using mutablemapOf() function and traverse it. In this example
we create three different types (MutableMap<Int, String>, MutableMap<String, String> and MutableMap<Any,
Any>) of MutableMap with different ways.

1. fun main(args: Array<String>) {


2.
3. val mutableMap1: MutableMap<Int, String> = mutableMapOf<Int, String>(1 to "Ashu", 4 to "Rohan", 2 to "Ajeet", 3 to
"Vijay")
4.
5. val mutableMap2: MutableMap<String, String> = mutableMapOf<String, String>()
6. mutableMap2.put("name", "Ashu")
7. mutableMap2.put("city", "Delhi")
8. mutableMap2.put("department", "Development")
9. mutableMap2.put("hobby", "Playing")
10. val mutableMap3: MutableMap<Any, Any> = mutableMapOf<Any, Any>(1 to "Ashu", "name" to "Rohsan", 2 to 200)
11. println(".....traverse mutableMap1........")
12. for (key in mutableMap1.keys) {
13. println("Key = ${key}, Value = ${mutableMap1[key]}")
14. }
15. println("......traverse mutableMap2.......")
16. for (key in mutableMap2.keys) {
17. println("Key = "+key +", "+"Value = "+mutableMap2[key])
18. }
19. println("......traverse mutableMap3......")
20. for (key in mutableMap3.keys) {
21. println("Key = ${key}, Value = ${mutableMap3[key]}")
22. }
23. }

Output:

.....traverse mutableMap1........
Key = 1, Value = Ashu
Key = 4, Value = Rohan
Key = 2, Value = Ajeet
Key = 3, Value = Vijay
This page by mytechtalk | Kotlin MutableMap Interface 135
......traverse mutableMap2.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......traverse mutableMap3......
Key = 1, Value = Ashu
Key = name, Value = Rohsan
Key = 2, Value = 200

Kotlin MutableMap Example - 2 put() and putAll()


The function put() and putAll() are used to add the elements in the MutableMap. put() function adds the single
element at a time where as putAll() function adds the collection type elements in the MutableMap. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6.
7.
8. val hashMap: HashMap<String,String> = hashMapOf<String,String>()
9. hashMap.put("department", "Development")
10. hashMap.put("hobby", "Playing")
11.
12. println("......traverse mutableMap.......")
13. for (key in mutableMap.keys) {
14. println("Key = "+key +", "+"Value = "+mutableMap[key])
15. }
16. mutableMap.putAll(hashMap)
17. println("......traverse mutableMap after mutableMap.putAll(hashMap).......")
18. for (key in mutableMap.keys) {
19. println("Key = "+key +", "+"Value = "+mutableMap[key])
20. }
21. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
......traverse mutableMap after mutableMap.putAll(hashMap).......
Key = name, Value = Ashu
Key = city, Value = Delhi

This page by mytechtalk | Kotlin MutableMap Interface 136


Key = department, Value = Development
Key = hobby, Value = Playing

Kotlin MutableMap Example - 3 containsKey()


The containsKey() function is used to check the specified key is present in MutableMap or not. If it contains the
specified key, it returns true otherwise it returns false. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.
9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = "+key +", "+"Value = "+mutableMap[key])
13. }
14.
15. println("......mutableMap.containsKey(\"city\").......")
16. println(mutableMap.containsKey("city"))
17. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......mutableMap.containsKey("city").......
true

Kotlin MutableMap Example - 4 containsValue()


The containsValue() function is used to check the specified value is present in MutableMap or not. This function
returns true if the map maps one or more keys for the given value else it returns false. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()

This page by mytechtalk | Kotlin MutableMap Interface 137


4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.
9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = "+key +", "+"Value = "+mutableMap[key])
13. }
14.
15. println(".......mutableMap.containsValue(\"Delhi\")......")
16. println(mutableMap.containsValue("Delhi"))
17. println(".......mutableMap.containsValue(\"Mumbai\")......")
18. println(mutableMap.containsValue("Mumbai"))
19. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.......mutableMap.containsValue("Delhi")......
true
.......mutableMap.containsValue("Mumbai")......
false

Kotlin MutableMap Example - 5 contains()


The contains() function is used to check either specified key of value is present in the MutableMap or not. If the
specified key or value is present in the MutableMap then it will returns true else it returns false. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.

This page by mytechtalk | Kotlin MutableMap Interface 138


9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = "+key +", "+"Value = "+mutableMap[key])
13. }
14.
15. println("......mutableMap.contains(\"city\").......")
16. println(mutableMap.contains("city"))
17.
18. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......mutableMap.contains("city").......
true

Kotlin MutableMap Example - 6 get(key)


The get(key) function is used to retrieve the corresponding value of specified key in the MutableMap. If no such
key is present in the MutableMap it returns null. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.
9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = "+key +", "+"Value = "+mutableMap[key])
13. }
14.
15. println(".......mutableMap.get(\"department\")......")
16. println(mutableMap.get("department"))
This page by mytechtalk | Kotlin MutableMap Interface 139
17.
18. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.......mutableMap.get("department")......
Development

Kotlin MutableMap Example - 7 getValue(key)


The getValue() function used to returns corresponding value of specified key of the MutableMap or it throws an
exception if no key found in map. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.
9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = ${key}, Value = ${mutableMap[key]}")
13. }
14.
15. println(".......mutableMap.getValue(\"department\")......")
16. println(mutableMap.getValue("department"))
17.
18. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.......mutableMap.getValue("department")......

This page by mytechtalk | Kotlin MutableMap Interface 140


Development

Kotlin MutableMap Example - 8 getOrDefault()


The getOrDefault() function returns corresponding value of specified key of MutableMap. If no such key exists
in the MutableMap then it returns default mention value. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.
9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = ${key}, Value = ${mutableMap[key]}")
13. }
14.
15. println(".......mutableMap.getOrDefault(\"name\", \"Default Value\")......")
16. println(mutableMap.getOrDefault("name", "default value"))
17. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.......mutableMap.getOrDefault("name", "Default Value")......
Ashu

Kotlin MutableMap Example - 9 count()


The count() function is used to returns the total number of elements present in the MutableMap. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")

This page by mytechtalk | Kotlin MutableMap Interface 141


5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.
9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = ${key}, Value = ${mutableMap[key]}")
13. }
14.
15. println(".....mutableMap.count()........")
16. println(mutableMap.count())
17. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.....mutableMap.count()........
4

Kotlin MutableMap Example - 10 remove(key) and remove(key,


value)
The remove(key) function is used to remove value corresponding to its mention key. Whereas remove(key,value)
function removes element containing key and value. The remove(key, value) function returns true if it remove
the specified key along with its value else it returns false. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.
9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
This page by mytechtalk | Kotlin MutableMap Interface 142
12. println("Key = ${key}, Value = ${mutableMap[key]}")
13. }
14.
15. println("......mutableMap.remove(\"city\").......")
16. println(mutableMap.remove("city"))
17.
18. println(".......mutableMap.remove(\"hobby\",\"Playing\")......")
19. println(mutableMap.remove("hobby","Playing"))
20.
21. println("......traverse mutableMap.......")
22. for (key in mutableMap.keys) {
23. println("Key = ${key}, Value = ${mutableMap[key]}")
24. }
25.
26. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......mutableMap.remove("city").......
Delhi
.......mutableMap.remove("hobby","Playing")......
true
......traverse mutableMap after remove.......
Key = name, Value = Ashu
Key = department, Value = Development

Kotlin MutableMap Example - 11 clear()


The clear() function is used to removes all the elements from the MutableMap. For example:

1. fun main(args: Array<String>) {


2.
3. val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
4. mutableMap.put("name", "Ashu")
5. mutableMap.put("city", "Delhi")
6. mutableMap.put("department", "Development")
7. mutableMap.put("hobby", "Playing")
8.

This page by mytechtalk | Kotlin MutableMap Interface 143


9. println("......traverse mutableMap.......")
10.
11. for (key in mutableMap.keys) {
12. println("Key = ${key}, Value = ${mutableMap[key]}")
13. }
14.
15. println("......mutableMap.clear().......")
16. println(mutableMap.clear())
17. println(mutableMap)
18. }

Output:

......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......mutableMap.clear().......
kotlin.Unit
{}

Kotlin Set Interface


Kotlin Set interface is a generic unordered collection of elements. Set interface does not support duplicate
elements. This interface is immutable in nature its methods supports read-only functionality of the set.

Set interface uses setOf() function to create the list of object of set interface which contains list of elements.

Set Interface declaration


1. interface Set<out E> : Collection<E> (source)

Properties of Set Interface


Properties Description

abstract val size: Int It returns the size of collection.

Functions of Set Interface


Kotlin Set interface has several functions. Some of its functions are mention below.

This page by mytechtalk | Kotlin Set Interface 144


Functions Description

abstract fun contains(element: E): Boolean It checks the mention element is present in this collection. If it
contains element, it returns true else returns false.

abstract fun containsAll(elements: It checks all the mention elements of specified collection are present
Collection<E>): Boolean in this collection. If it contains element, it returns true else returns
false.

abstract fun isEmpty(): Boolean It returns true if the collection is empty (contains no elements)
otherwise it returns false.

abstract fun iterator(): Iterator<E> It returns an iterator over the elements of set object.

fun <T> Iterable<T>.all(predicate: (T) -> It returns true if all the elements matches with given predicate.
Boolean): Boolean

fun <T> Iterable<T>.any(): Boolean It returns true if the collection contains at least one element.

fun <T> Iterable<T>.count(predicate: (T) - It returns the total number of elements matching with given predicate.
> Boolean): Int

fun <T> Iterable<T>.distinct(): List<T> It returns a list which contains only distinct elements from the given
collection.

fun <T> Iterable<T>.drop(n: Int): List<T> It returns a list which contains all elements except first n elements.

fun <T> Iterable<T>.elementAtOrElse( It returns an element at given index or result of calling the
index: Int, defaultValue function if the index is out bounds in current collection.
defaultValue: (Int) -> T

This page by mytechtalk | Kotlin Set Interface 145


): T

fun <T> Iterable<T>.filter( It returns a list which contains only those elements matches with
predicate: (T) -> Boolean given predicate.
): List<T>

fun <T> Iterable<T>.filterIndexed( It returns a list which contains only those elements matches with
predicate: (index: Int, T) -> Boolean given predicate.
): List<T>

fun <T> Iterable<T>.filterNot( It returns a list which contains only those elements which does not
predicate: (T) -> Boolean matches with given predicate.
): List<T>

fun <T> Iterable<T>.find(predicate: (T) -> It returns the first element which matches with given predicate,
Boolean): T? or null if no such element was found.

fun <T> Iterable<T>.findLast(predicate: It returns the last element which matches with given predicate,
(T) -> Boolean): T? or null if no such element was found.

fun <T> Iterable<T>.first(): T It returns the first element.

fun <T> Iterable<T>.first(predicate: (T) -> It returns the first element which matches the given predicate.
Boolean): T

fun <T> Iterable<T>.firstOrnull(): T? It returns the first element or null if collection is empty.

fun <T> Iterable<T>.indexOf(element: T): It returns the first index of given element, or -1 if element does not
Int contains in collection.

This page by mytechtalk | Kotlin Set Interface 146


fun <T> Iterable<T>.indexOfFirst( It returns the index of first element which matches the given
predicate: (T) -> Boolean predicate, or -1 if the element does not contains in collection.
): Int

fun <T> Iterable<T>.indexOfLast( It returns the index of last element which matches the given
predicate: (T) -> Boolean predicate, or -1 if the element does not contains in collection.
): Int

infix fun <T> Iterable<T>.intersect( It returns a set which contains all elements present in both this set and
other: Iterable<T> given collection.
): Set<T>

fun <T> Collection<T>.isNotEmpty(): It returns true if is not empty.


Boolean

fun <T> Iterable<T>.last(): T It returns the last element.

fun <T> Iterable<T>.last(predicate: (T) -> It returns the last element which matches with given predicate.
Boolean): T

fun <T> Iterable<T>.lastIndexOf(element: It returns the last index of given element, or -1 if element does not
T): Int exist in collection.

fun <T> Iterable<T>.lastOrnull(): T? It returns the last element of collection, or null if collection is empty.

fun <T> Iterable<T>.lastOrnull(predicate: It returns the last element after matching the given predicate, or
(T) -> Boolean): T? returns null if no such element found in collection.

fun <T : Comparable<T>> It returns the largest element or null if no elements in collection.
Iterable<T>.max(): T?

This page by mytechtalk | Kotlin Set Interface 147


fun <T, R : Comparable<R>> It returns the first element yielding the largest value of the given
Iterable<T>.maxBy( function, or it returns null if there are no elements in collection.
selector: (T) -> R
): T?

fun <T : Comparable<T>> It returns the smallest element or null if there is no element in the
Iterable<T>.min(): T? collection.

fun <T, R : Comparable<R>> It returns the first element which gives the smallest value of the given
Iterable<T>.minBy( function or null if there are no elements.
selector: (T) -> R
): T?

operator fun <T> Set<T>.minus(element: It returns a set which contains all the elements of original set except
T): Set<T> those given element.

operator fun <T> Set<T>.minus(elements: It returns a set which contains all the elements of original set except
Iterable<T>): Set<T> those given elements collection.

operator fun <T> It returns a list which contains all the elements of original collection
Iterable<T>.minus(element: T): List<T> except those contained in the given elements array.

fun <T> Set<T>.minusElement(element: It returns a set which contains all the elements of original set except
T): Set<T> those given element.

fun <T> It returns a list which contains all the elements of original collection
Iterable<T>.minusElement(element: T): except the first occurrence of the given element.
List<T>

operator fun <T> Set<T>.plus(element: T): It returns a set of all elements of original set as well as the given

This page by mytechtalk | Kotlin Set Interface 148


Set<T> element if it is not already present in the set.

operator fun <T> Set<T>.plus(elements: It returns a set which contains all the elements of original set as well
Iterable<T>): Set<T> as the given elements collection which are not already present in the
set. The returned set preserves the iteration of element in the same
order of the original set.

operator fun <T> It returns a list which contains all the elements of the original
Iterable<T>.plus(element: T): List<T> collection as well as the given element.

fun <T> Set<T>.plusElement(element: T): It returns a set which contains all the elements of the original set as
Set<T> well as the given element.

fun <T> Iterable<T>.plusElement(element: It returns a list which contains all the elements of the original
T): List<T> collection as well as the given element.

fun <T> Iterable<T>.reversed(): List<T> It returns a list with elements in the reverse order.

fun <T> Iterable<T>.single(): T It returns the single element, or it throws an exception if the
collection has more than one elements or empty.

fun <T> Iterable<T>.singleOrnull(): T? It returns a single element, or null if the collection has more than one
element or it is empty.

Kotlin Set Interface Example 1


Let create an example of declaring and traversing set element using setOf() function. In this example we create a
set of Int type non generic and another generic set of Any type.

1. fun main(args: Array<String>){


2. val intSet = setOf(2,6,4,29,4,5)
3. val mySet: Set<Any> = setOf(2,6,4,29,4,5,"Ashu","Ajay")
4. println(".......print Int set.........")
This page by mytechtalk | Kotlin Set Interface 149
5. for(element in intSet){
6. println(element)
7. }
8. println(".......print Any set.........")
9. for(element in mySet){
10. println(element)
11. }
12.
13. }

Output:

.......print Int set.........


2
6
4
29
5
.......print Any set.........
2
6
4
29
5
Ashu
Ajay

In the above example we declare element 4 twice in both intSet and mySet but while traversing them they print
the element 4 only once. This is because the set interface does not support duplicate elements.

Kotlin Set Interface Example 2 - contains() and containsAll()


The contains() function checks the given element is present in current set or not. If it is contains in the set, the set
returns true else returns false. Whereas containsAll() function checks all the elements of collection type are
present in the current set or not. If the set contains all elements of collection type it returns true else false.

1. fun main(args: Array<String>){


2. val mySet: Set<Any> = setOf(2,6,4,29,5,"Ashu","Ajay")
3. val intSet = setOf(6,4,29)
4. println(".......print Any set.........")
5. for(element in mySet){
6. println(element)
7. }
8. println("...mySet.contains\"Ashu\"...")
9. println(mySet.contains("Ashu"))

This page by mytechtalk | Kotlin Set Interface 150


10. println("...mySet.contains(20)...")
11. println(mySet.contains(20))
12. println("...mySet.containsAll(intSet)...")
13. println(mySet.containsAll(intSet))
14.
15. }

Output:

.......print Any set.........


2
6
4
29
5
Ashu
Ajay
...mySet.contains"Ashu"...
true
...mySet.contains(20)...
false
...mySet.containsAll(intSet)...
true

Kotlin Set Interface Example 3 - isEmpty() and isNotEmpty()


The isEmpty() function checks the current set is empty. If the set is empty the isEmpty() function returns true
otherwise it returns false. And isNotEmpty() checks the current set is not empty. If the set is not empty the
isNotEmpty() function returns true else return false.

1. fun main(args: Array<String>){


2. val mySet: Set<Any> = setOf(2,6,4,29,5,"Ashu","Ajay")
3. println(".......print Any set.........")
4. for(element in mySet){
5. println(element)
6. }
7.
8. println("...mySet.isEmpty()...")
9. println(mySet.isEmpty())
10.
11. println("...mySet.isNotEmpty()...")
12. println(mySet.isNotEmpty())
13.
14. }

This page by mytechtalk | Kotlin Set Interface 151


Output:

.......print Any set.........


2
6
4
29
5
Ashu
Ajay
...mySet.isEmpty()...
false
...mySet.isNotEmpty()...
true

Kotlin Set Interface Example 4 - drop()


The drop() function returns all the element except the first n elements of collection.

1. fun main(args: Array<String>){


2. val mySet: Set<Any> = setOf(2,6,4,29,4,5,"Ajay","Ashu","Ajay")
3. println(".......print Any set.........")
4. for(element in mySet){
5. println(element)
6. }
7. val remainList= mySet.drop(4)
8. println(".......print Set after mySet.drop(4).........")
9. for(element in remainList){
10. println(element)
11. }
12. }

Output:

.......print Any set.........


2
6
4
29
5
Ajay
Ashu
.......print Set after mySet.drop(4).........
5
Ajay
Ashu

This page by mytechtalk | Kotlin Set Interface 152


Kotlin Set Interface Example 5 - elementAt() and elementAtOrNull()
The elementAt() function return element at given index and elementAtOrNull() function also return the element
at given index , but if specified index does not contain element it returns null.

1. fun main(args: Array<String>){


2. val mySet: Set<Any> = setOf(2,6,4,29,4,5,"Ajay","Ashu","Ajay")
3.
4. println(".......print Any set.........")
5. for(element in mySet){
6. println(element)
7. }
8.
9. println(".......print mySet.elementAt(3).........")
10. println(mySet.elementAt(3))
11.
12. println(".......print mySet.elementAtOrNull(5).........")
13. println(mySet.elementAtOrNull(5))
14. }

Output:

.......print Any set.........


2
6
4
29
5
Ajay
Ashu
.......print mySet.elementAt(3).........
29
.......print mySet.elementAtOrNull(5).........
Ajay

Kotlin MutableSet Interface


Kotlin MutableSet interface is a generic unordered collection of elements. MutableSet interface does not support
duplicate elements. This interface is mutable so its methods support read-write functionality supports adding and
removing elements.

Set interface uses mutableSetOf() function to create the list of object of set interface which contains list of
elements.

MutableSet Interface declaration


1. interface MutableSet<E> : Set<E>, MutableCollection<E> (source)
This page by mytechtalk | Kotlin MutableSet Interface 153
Inherited Properties of MutableSet Interface
Properties Description

abstract val size: Int It returns the size of collection.

Functions of MutableSet Interface


Kotlin MutableSet interface has several functions. Some of its functions are mention below.

Functions Description

abstract fun add(element: E): Boolean It adds the given element to the collection.

abstract fun addAll(elements: It adds all the elements given collection to the current collection.
Collection<E>): Boolean

abstract fun clear() It removes all the elements from this collection.

abstract fun iterator(): MutableIterator<E> It returns an iterator over the elements of this object.

abstract fun remove(element: E): Boolean It removes a single specified element from this collection, if it is
present in collection.

abstract fun removeAll(elements: It removes all the elements from current collection which are given
Collection<E>): Boolean in collection.

abstract fun retainAll(elements: It retains only those elements in current collection which are present
Collection<E>): Boolean in specified collection.

abstract fun contains(element: E): Boolean It checks the specified element is contained in current collection.

This page by mytechtalk | Kotlin MutableSet Interface 154


abstract fun containsAll(elements: It checks all the elements of specified collection are present in
Collection<E>): Boolean current collection.

abstract fun isEmpty(): Boolean If collection is empty (not containing any element) it returns true,
otherwise it returns false.

fun <T> Iterable<T>.any(): Boolean It returns true if collection contains at least one element.

fun <T> Iterable<T>.any(predicate: (T) -> It returns true if at least element matches the given the given
Boolean): Boolean predicate.

fun <T> Iterable<T>.distinct(): List<T> It returns a list which contains only distinct elements from the given
collection.

fun <T> Iterable<T>.drop(n: Int): List<T> It returns a list which contains all elements except first n elements.

fun <T> Iterable<T>.elementAt(index: Int): It returns an element at given index or throw an


T IndexOutOfBoundException if given index is not present in
collection.

fun <T> Iterable<T>.elementAtOrElse( It returns an element at given index or result of calling the
index: Int, defaultValue function if the index is out bounds in current
defaultValue: (Int) -> T collection.
): T

fun <T : Comparable<T>> It returns the largest element or null if there is no element in the
Iterable<T>.max(): T? collection.

fun <T : Comparable<T>> It returns the smallest element or null if there is no element in the
Iterable<T>.min(): T? collection.

This page by mytechtalk | Kotlin MutableSet Interface 155


fun <T> MutableCollection<out It removes the single specified element if it in present in current
T>.remove(element: T): Boolean collection.

fun <T> MutableCollection<out It removes all the elements of current collection which are contained
T>.removeAll( in specified collection.
elements: Collection<T>
): Boolean

fun <T> MutableCollection<out It retains all the elements in current collection which are contained
T>.retainAll( in specified collection.
elements: Collection<T>
): Boolean

fun <T> Iterable<T>.reversed(): List<T> It returns the elements in reversed order.

Kotlin MutableSet Interface Example 1


Let's create an example of MutableSet declaring and traversing its elements.

1. fun main(args: Array<String>) {


2. val intmutableSet = mutableSetOf<Int>(2, 6, 4, 29, 4, 5)
3. val anymutableSet: Set<Any> = setOf(2, 6, 4, 29, 4, 5, "Ajay", "Ashu", "Ajay")
4. println("....intmutableSet....")
5. for(element in intmutableSet){
6. println(element)
7. }
8. println("....anymutableSet......")
9. for(element in anymutableSet){
10. println(element)
11. }
12. }

Output:

....intmutableSet....
2

This page by mytechtalk | Kotlin MutableSet Interface 156


6
4
29
5
....anymutableSet......
2
6
4
29
5
Ajay
Ashu

In the above example, elements "4" and "Ajay" are declared twice. But while traversing these MutableSet they
are printed only once, this is because MutableSet interface does not support duplicate elements.

Kotlin MutableSet Interface Example 2 - add() and addAll()


1. fun main(args: Array<String>) {
2. val intmutableSet = mutableSetOf<Int>(2, 6, 4, 29, 4, 5)
3. val mutableSet: MutableSet<Int> = mutableSetOf<Int>(6,8,11,22)
4.
5. println("....intmutableSet....")
6. for(element in intmutableSet){
7. println(element)
8. }
9. intmutableSet.add(10)
10. println("....intmutableSet.add(10)....")
11. for(element in intmutableSet){
12. println(element)
13. }
14.
15. intmutableSet.addAll(mutableSet)
16. println("....intmutableSet.addAll(mutableSet)....")
17. for(element in intmutableSet){
18. println(element)
19. }
20. }

Output:

....intmutableSet....
2
6
4
29
5

This page by mytechtalk | Kotlin MutableSet Interface 157


....intmutableSet.add(10)....
2
6
4
29
5
10
....intmutableSet.addAll(mutableSet)....
2
6
4
29
5
10
8
11
22

Kotlin MutableSet Interface Example 3 - remove() and removeAll()


1. fun main(args: Array<String>) {
2. val intmutableSet = mutableSetOf<Int>(2, 6, 4, 29, 4, 5)
3. val mutableSet: MutableSet<Int> = mutableSetOf<Int>(6,8,11,22)
4.
5. println("....intmutableSet....")
6. for(element in intmutableSet){
7. println(element)
8. }
9. intmutableSet.remove(29)
10. println("....intmutableSet.remove(29)....")
11. for(element in intmutableSet){
12. println(element)
13. }
14. intmutableSet.removeAll(mutableSet)
15. println("....intmutableSet.removeAll(mutableSet)....")
16. for(element in intmutableSet){
17. println(element)
18. }
19. }

Output:

....intmutableSet....
2
6
4
29
5

This page by mytechtalk | Kotlin MutableSet Interface 158


....intmutableSet.remove(29)....
2
6
4
5
....intmutableSet.removeAll(mutableSet)....
2
4
5

Kotlin MutableSet Interface Example 4 - contains() and containsAll()


1. fun main(args: Array<String>) {
2. val mutableSet1 = mutableSetOf<Int>(2, 6, 4, 29, 4, 5)
3. val mutableSet2: MutableSet<Int> = mutableSetOf<Int>(6,8,11,22)
4. val mutableSet3: MutableSet<Int> = mutableSetOf<Int>(2,4,6)
5.
6. println("....mutableSet1....")
7. for(element in mutableSet1){
8. println(element)
9. }
10. println("....mutableSet2....")
11. println(mutableSet2)
12. println("....mutableSet3....")
13. println(mutableSet3)
14. println("....mutableSet1.contains(29)....")
15. println(mutableSet1.contains(29))
16.
17. println("....mutableSet1.containsAll(mutableSet2))....")
18. println(mutableSet1.containsAll(mutableSet2))
19. println("....mutableSet1.containsAll(mutableSet3))....")
20. println(mutableSet1.containsAll(mutableSet3))
21. }

Output:

....mutableSet1....
2
6
4
29
5
....mutableSet2....
[6, 8, 11, 22]
....mutableSet3....
[2, 4, 6]
....mutableSet1.contains(29)....

This page by mytechtalk | Kotlin MutableSet Interface 159


true
....mutableSet1.containsAll(mutableSet2))....
false
....mutableSet1.containsAll(mutableSet3))....
true

Kotlin MutableSet Interface Example 5 - isEmpty() and any()


1. fun main(args: Array<String>) {
2. val mutableSet1 = mutableSetOf<Int>(2, 6, 4, 29, 4, 5)
3.
4. println("....mutableSet1....")
5. for(element in mutableSet1){
6. println(element)
7. }
8. println("....mutableSet1.isEmpty()....")
9. if(mutableSet1.isEmpty())
10. println("mutableSet1 is empty, not contain any element")
11. else
12. println("mutableSet1 is not empty, contains element")
13.
14. println("....mutableSet1.any()....")
15. if(mutableSet1.any())
16. println("mutableSet1 contain at least one or more elements")
17. else
18. println("mutableSet1 not contain any element")
19. }

Output:

....mutableSet1....
2
6
4
29
5
....mutableSet1.isEmpty()....
mutableSet1 is not empty, contains element
....mutableSet1.any()....
mutableSet1 contain at least one or more elements

Kotlin MutableSet Interface Example 6 - first(), indexOf() and drop()


1. fun main(args: Array<String>) {
2. val mutableSet1 = mutableSetOf<Int>(2, 6, 4, 29, 4, 5)
3.

This page by mytechtalk | Kotlin MutableSet Interface 160


4. println("....mutableSet1....")
5. for(element in mutableSet1){
6. println(element)
7. }
8. println("....mutableSet1.first()....")
9. println(mutableSet1.first())
10.
11. println("...mutableSet1.indexOf(4)...")
12. println(mutableSet1.indexOf(4))
13.
14. println("...mutableSet1.drop(3)...")
15. println(mutableSet1.drop(3))
16. }

Output:

....mutableSet1....
2
6
4
29
5
....mutableSet1.first()....
2
...mutableSet1.indexOf(4)...
2
...mutableSet1.drop(3)...
[29, 5]

Kotlin HashSet class


Kotlin HashSet is class of collection which extends AbstractMutableSet class and implements Set interface. The
HashSet class store elements using hashing mechanism. It support both read and write functionality. It does not
support duplicate value and does not make guarantees about the order sequence of element.

HashSet class declaration


1. open class HashSet<E> : AbstractMutableSet<E> (source)

Constructor of Kotlin HashSet class


Constructor Description

HashSet() It constructs an empty HashSet instance

This page by mytechtalk | Kotlin HashSet class 161


HashSet(initialCapacity: Int, loadFactor: Float = It is used to constructs a HashSet of specified capacity.
0f)

HashSet(elements: Collection<E>) It constructs a HashSet instance using elements of specified


collection.

Functions of Kotlin HashSet class


Functions Description

open fun add(element: E): Boolean It adds the given element to the collection.

open operator fun It checks the specified element is present in current collection.
contains(element: E): Boolean

open fun isEmpty(): Boolean It checks the current collection is empty (not contain any element). If found
collection is empty returns true otherwise false.

open fun iterator(): It returns an iterator over the elements of current object.
MutableIterator<E>

open fun remove(element: E): It removes the mention element if present in current collection. It returns true
Boolean if it removes otherwise false.

open fun clear() It deletes all the elements from this collection.

Property of Kotlin HashSet class


Property Description

This page by mytechtalk | Kotlin HashSet class 162


open val size: Int This property is used to return the size of HashSet collection.

Kotlin HashSet Example 1- capacity


Let's create an example of HashSet defining it capacity. Capacity defines the total number of element to be added
in the HashSet. It can be increase of decrease later according to need.

1. fun main(args: Array<String>){


2. var hashSet = HashSet<Int>(6)
3. hashSet.add(2)
4. hashSet.add(13)
5. hashSet.add(6)
6. hashSet.add(5)
7. hashSet.add(2)
8. hashSet.add(8)
9. println("......traversing hashSet......")
10. for (element in hashSet){
11. println(element)
12. }
13. }

Output:

......traversing hashSet......
8
2
13
5
6

Kotlin HashSet Example 2 - generic


For more specific we can provide the generic types of HashSet class using its method hashSetOf<T>().

1. fun main(args: Array<String>){


2. var hashSetOf1 = hashSetOf<Int>(2,13,6,5,2,8)
3. var hashSetOf2: HashSet<String> = hashSetOf<String>("Vijay","Ashu" ,"Vijay","Roshan")
4. println("......traversing hashSetOf1......")
5. for (element in hashSetOf1){
6. println(element)
7. }

This page by mytechtalk | Kotlin HashSet class 163


8. println("......traversing hashSetOf2......")
9. for (element in hashSetOf2){
10. println(element)
11. }
12. }

Output:

......traversing hashSetOf1......
8
2
13
5
6
......traversing hashSetOf2......
Ashu
Roshan
Vijay

Kotlin HashSet Example 3 - add() and addAll()


The add() function is used to add the element in the HashSet instance whereas addAll() function add all the
elements of specified collection to HashSet.

1. fun main(args: Array<String>){


2. var hashSet = HashSet<Int>(3)
3. val intSet = setOf(6,4,29)
4. hashSet.add(2)
5. hashSet.add(13)
6. hashSet.add(6)
7. hashSet.add(5)
8. hashSet.add(2)
9. hashSet.add(8)
10. println("......traversing hashSet......")
11. for (element in hashSet){
12. println(element)
13. }
14. hashSet.addAll(intSet)
15. println("......traversing hashSet after hashSet.addAll(intSet)......")
16. for (element in hashSet){
17. println(element)
18. }
19. }

This page by mytechtalk | Kotlin HashSet class 164


Output:

......traversing hashSet......
8
2
13
5
6
......traversing hashSet after hashSet.addAll(intSet)......
2
4
5
6
8
13
29

Kotlin HashSet Example 4 - size, contains() and containsAll()


The size property returns a total elements present in HashMap. The contains() function returns true if the
mention element in it is contained in collection whereas containsAll() function checks all the elements of
specified collection is contained in this collection.

1. fun main(args: Array<String>){


2. var hashSetOf1: HashSet<Int> = hashSetOf<Int>(2,6,13,4,29,15)
3. val mySet = setOf(6,4,29)
4.
5. println("......traversing hashSetOf1......")
6. for (element in hashSetOf1){
7. println(element)
8. }
9. println(".....hashSetOf1.size.....")
10. println(hashSetOf1.size)
11. println(".....hashSetOf1.contains(13).....")
12. println(hashSetOf1.contains(13))
13. println("....hashSetOf1.containsAll(mySet)...")
14. println(hashSetOf1.containsAll(mySet))
15. }

Output:

......traversing hashSetOf1......
2
4
13
29
6
15
.....hashSetOf1.size.....

This page by mytechtalk | Kotlin HashSet class 165


6
.....hashSetOf1.contains(13).....
true
....hashSetOf1.containsAll(mySet)...
true

Kotlin HashSet Example 5 - remove() and removeAll()


The remove() function removes the specified element from the collection if it is present whereas removeAll()
function removes all the specified elements from current collection if they are present.

1. fun main(args: Array<String>){


2. var hashSetOf1: HashSet<Int> = hashSetOf<Int>(2,6,13,4,29,15)
3. val mySet = setOf(6,4,29)
4.
5. println("......traversing hashSetOf1......")
6. for (element in hashSetOf1){
7. println(element)
8. }
9. println(".....hashSetOf1.remove(6)......")
10. println(hashSetOf1.remove(6))
11. println("......traversing hashSetOf1 after remove(6)......")
12. for (element in hashSetOf1){
13. println(element)
14. }
15. println("......hashSetOf1.removeAll(mySet)......")
16. println(hashSetOf1.removeAll(mySet))
17. println("......traversing hashSetOf1 after removeAll(mySet)......")
18. for (element in hashSetOf1){
19. println(element)
20. }
21. }

Output:

......traversing hashSetOf1......
2
4
13
29
6
15
.....hashSetOf1.remove(6)......
true
......traversing hashSetOf1 after remove(6)......

This page by mytechtalk | Kotlin HashSet class 166


2
4
13
29
15
......hashSetOf1.removeAll(mySet)......
true
......traversing hashSetOf1 after removeAll(mySet)......
2
13
15

Kotlin HashSet Example 6 - isEmpty() and isNotEmpty()


The isEmpty() function checks the current collection is empty whereas isNotEmpty() function checks the current
collection is not empty.

1. fun main(args: Array<String>){


2. var hashSetOf1: HashSet<Int> = hashSetOf<Int>(2,6,13,4,29,15)
3.
4. println("......traversing hashSetOf1......")
5. for (element in hashSetOf1){
6. println(element)
7. }
8. println(".....hashSetOf1.isEmpty()....")
9. if(hashSetOf1.isEmpty()){
10. println("hash set is empty")
11. }
12. else{
13. println("hash set is not empty")
14. }
15. println(".....hashSetOf1.isNotEmpty()....")
16. if(hashSetOf1.isNotEmpty()){
17. println("hash set is not empty")
18. }
19. else{
20. println("hash set is empty")
21. }
22. }

Output:

......traversing hashSetOf1......
2
4
This page by mytechtalk | Kotlin HashSet class 167
13
29
6
15
.....hashSetOf1.isEmpty()....
hash set is not empty
.....hashSetOf1.isNotEmpty()....
hash set is not empty

Kotlin Annotations
Annotations are used to attach metadata to classes, interface, parameters, and so on at compile time. Annotation
can be used by compiler which reflects at runtime. We can change the meaning of the data or program according
to annotation values.

Kotlin Meta-annotations
We can add meta-info while declaring annotation. Following are some meta-annotations:

Annotation Usage
Name

@Target It targets all the possible kinds of elements which can be annotated with the annotation.

@Retention It specifies whether the annotation is stored in the compiled class files or whether it is
visible through reflection at run time.

@Repeatable This meta-annotation determines that an annotation is applicable twice or more on a


single code element.

@MustBeDocumented This meta-document specifies that the annotation is the part of the public API and should
be included in the class or method.

Example of using annotation


1. @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,
This page by mytechtalk | Kotlin Annotations 168
2. AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)
3. @Retention(AnnotationRetention.SOURCE)
4. @MustBeDocumented
5. annotation class MyClass

Declaring an annotation
Annotation is declared by placing annotation modifier in front of a class.

1. annotation class MyClass

Annotate a constructor
It is also possible to annotate the constructor of a class. This is done by adding the constructor keyword for
constructor declaration and placing the annotation before it.

1. class MyClass@Inject constructor( dependency: MyDependency){


2. //. . .
3. }

Annotate property assessors


1. class MyClass{
2. var a: MyDependency? = null
3. @Inject set
4. }

Using constructor as annotation


We can also use constructor as an annotation. Using constructor as annotation takes parameters.

1. annotation class MyClass(val why: String)


2. @MyClass("parameter") class Foo{
3. }

The parameters which are used as an annotation cannot be nullable types. This is because the JVM does not
support null as a value for an annotation attribute.

We can also use one annotation as a parameter to another annotation, at such situation it cannot takes the prefix
@ character. Forexample:

1. annotation class ReplaceWith(val expression: String)


2. annotation class Deprecated(
This page by mytechtalk | Kotlin Annotations 169
3. val message: String,
4. val replaceWith: ReplaceWith = ReplaceWith(""))
5. @Deprecated("This function is deprecated, use === instead", ReplaceWith("this === other"))

Kotlin also specifies that a class can takean argument of an annotation by using a KClass. The Kotlin compiler
automatically converts it into java class, which leads to see the annotations and arguments normally.

1. import kotlin.reflect.KClass
2. annotation class MyClass(val arg1: KClass<*>, val arg2: KClass<out Any>)
3. @MyClass(String::class, Int::class) class Foo

Example of using TYPE annotation


Creating a java annotation interface Ann.java

1. import java.lang.annotation.ElementType;
2. import java.lang.annotation.Retention;
3. import java.lang.annotation.RetentionPolicy;
4. import java.lang.annotation.Target;
5. @Target(ElementType.TYPE)
6. @Retention(RetentionPolicy.RUNTIME)
7. @interface Ann{
8. int value();
9. }

Create a MyClass.kt class which uses the annotation interface Ann.

1. @Ann(value = 10)
2. class MyClass{
3.
4. }
5. fun main (args: Array<String>){
6. var c = MyClass()
7. var x = c.javaClass.getAnnotation(Ann::class.java)
8. if(x!=null){
9. println("Value:"+x?.value)
10. }
11. }

Output:

This page by mytechtalk | Kotlin Annotations 170


Value: 10

Kotlin Reflection
Reflection is a set of language and library features that examines the structure of program at runtime. Kotlin
makes functions and properties as first-class citizen in the language and examine these functions and properties
at runtime.

Class Reference
Class reference is used to obtain the reference of KClass object. To obtain the reference of statically Kclass, we
should use the class literal(i.e. use double colons).

Syntax of class reference:

1. val c1 = String::class
2. val c2 = MyClass::class

The reference value is a class type of KClass. KClass class reference is not the same as a Java class reference.
We obtain the Java class reference by using .java property on a KClass instance.

Note: KClass represents a class and provides examination capabilities. To obtain the instance of this
class use syntax ::class.

Functional Reference
Kotlin functional is used to obtain the reference of function using double colons. The reference of function can
be used in another function as a parameter. To use this reference in another function we use the :: operator:

1. fun isPositive(x: Int) = x> 0


1. fun isPositive(x: Int) = x> 0
2. val number = listOf(-10,-5,0,5,10)
3. print(number.filter(::isPositive))

Kotlin functional reference example


1. fun main(args: Array<String>) {
2. fun isPositive(x: Int) = x > 0
3. val numbers = listOf(-10, -5, 0, 5, 10)

This page by mytechtalk | Kotlin Reflection 171


4. println(numbers.filter(::isPositive))
5. }

Output:

[5,10]

In the above program ::isPositive is a value of function type (Int) -> Boolean.

Overloaded function reference operator (::)


The operator :: can be used with overload function when the expected type is known from the context. For
example:

Create a function isPositive() which takes two different types Int and String and call this function with different
type parameter.

1. fun main(args: Array<String>) {


2. fun isPositive(x: Int) = x > 0
3. fun isPositive(s: String) = s== "kotlin" || s == "Kotlin"
4.
5. val numbers = listOf(-10,-5,0,5,10)
6. val strings = listOf("kotlin", "program")
7.
8. println(numbers.filter(::isPositive))
9. println(strings.filter(::isPositive))
10. }

Output:

[5, 10]
[kotlin]

Property Reference
We can also access the properties as first-class object in Kotlin, to access object property we can use :: operator:

To evaluate the property object of type KProperty<Int> we use the expression ::variableName. The expression
::variableName allow to retrieve its property name by using name and readits value using get() function.

To reset the value of mutable type property, reference property has set() method.

1. fun main(args: Array<String>) {


2. println(::x.get())

This page by mytechtalk | Kotlin Reflection 172


3. println(::x.name)
4. println(::y.set(10))
5. }
6. val x = 5
7. var y = 5

Output:

5
x
10

Access the property of member class:


Property reference also access the property of other member of class. For example:

1. class A(val x: Int)


2. fun main(args: Array<String>) {
3. val prop = A::x
4. println(prop.get(A(5)))
5. }

Output:

Kotlin Class and Object


Kotlin supports both object oriented programming (OOP) as well as functional programming. Object oriented
programming is based on real time objects and classes. Kotlin also support pillars of OOP language such as
encapsulation, inheritance and polymorphism.

Kotlin Class
Kotlin class is similar to Java class, a class is a blueprint for the objects which have common properties. Kotlin
classes are declared using keyword class. Kotlin class has a class header which specifies its type parameters,
constructor etc. and the class body which is surrounded by curly braces.

Syntax of Kotlin class declaration


1. class className{ // class header
2. // property
3. // member function
4. }

This page by mytechtalk | Kotlin Class and Object 173


In above example, class className is an empty constructor. It is generated by compiler automatically but if we
want to provide a constructor, we need to write a constructor keyword followed by class name as:

1. class className constructor(){ // class header


2. // property
3. // member function
4. }

Example of Kotlin class


1. class account {
2. var acc_no: Int = 0
3. var name: String? = null
4. var amount: Float = 0f
5.
6. fun deposit() {
7. //deposite code
8. }
9.
10. fun withdraw() {
11. // withdraw code
12. }
13.
14. fun checkBalance() {
15. //balance check code
16. }
17.
18. }

The account class has three properties acc_no, name, amount and three member functions deposit(),
withdraw(),checkBalance().

In Kotlin, property must be initialize or declare as abstract. In above class, properties acc_no initialize as 0, name
as null and amount as 0f.

Kotlin Object
Object is real time entity or may be a logical entity which has state and behavior. It has the characteristics:

o state: it represents value of an object.

o behavior: it represent the functionality of an object.

This page by mytechtalk | Kotlin Class and Object 174


Object is used to access the properties and member function of a class. Kotlin allows to create multiple object of
a class.

Create an object
Kotlin object is created in two steps, the first is to create reference and then create an object.

1. var obj1 = className()

Creating multiple object

1. var obj1 = className()


2. var obj2 = className()

Here obj1 and obj2 are reference and className() is an object.

Access class property and member function


Properties and member function of class are accessed by . operator using object. For example:

1. obj.deopsit()
2. obj.name = Ajay

Let's create an example, which access the class property and member function using . operator.

1. class Account {
2. var acc_no: Int = 0
3. var name: String = ""
4. var amount: Float = 0.toFloat()
5. fun insert(ac: Int,n: String, am: Float ) {
6. acc_no=ac
7. name=n
8. amount=am
9. println("Account no: ${acc_no} holder :${name} amount :${amount}")
10. }
11.
12. fun deposit() {
13. //deposite code
14. }
15.
16. fun withdraw() {

This page by mytechtalk | Kotlin Class and Object 175


17. // withdraw code
18. }
19.
20. fun checkBalance() {
21. //balance check code
22. }
23.
24. }
25. fun main(args: Array<String>){
26. Account()
27. var acc= Account()
28. acc.insert(832345,"Ankit",1000f) //accessing member function
29. println("${acc.name}") //accessing class property
30. }

Output:

Account no: 832345 holder :Ankit amount :1000.0


Ankit

Kotlin Nested class and Inner class


Kotlin Nested class
Nested class is such class which is created inside another class. In Kotlin, nested class is by default static, so its
data member and member function can be accessed without creating an object of class. Nested class cannot be
able to access the data member of outer class.

1. class outerClass{
2. //outer class code
3. class nestedClass{
4. //nested class code
5. }
6. }

Kotlin Nested Class Example


1. class outerClass{
2. private var name: String = "Ashu"
3. class nestedClass{
4. var description: String = "code inside nested class"

This page by mytechtalk | Kotlin Nested class and Inner class 176
5. private var id: Int = 101
6. fun foo(){
7. // print("name is ${name}") // cannot access the outer class member
8. println("Id is ${id}")
9. }
10. }
11. }
12. fun main(args: Array<String>){
13. // nested class must be initialize
14. println(outerClass.nestedClass().description) // accessing property
15. var obj = outerClass.nestedClass() // object creation
16. obj.foo() // access member function
17. }

Output:

code inside nested class


Id is 101

Kotlin Inner class


Inner class is a class which is created inside another class with keyword inner. In other words, we can say that a
nested class which is marked as "inner" is called inner class.

Inner class cannot be declared inside interfaces or non-inner nested classes.

1. class outerClass{
2. //outer class code
3. inner class innerClass{
4. //nested class code
5. }
6. }

The advantage of inner class over nested class is that, it is able to access members of outer class even it is
private. Inner class keeps a reference to an object of outer class.

Kotlin Inner Class Example


1. class outerClass{
2. private var name: String = "Ashu"
3. inner class innerClass{
4. var description: String = "code inside inner class"

This page by mytechtalk | Kotlin Nested class and Inner class 177
5. private var id: Int = 101
6. fun foo(){
7. println("name is ${name}") // access the outer class member even private
8. println("Id is ${id}")
9. }
10. }
11. }
12. fun main(args: Array<String>){
13. println(outerClass().innerClass().description) // accessing property
14. var obj = outerClass().innerClass() // object creation
15. obj.foo() // access member function
16.
17. }

Output:

code inside inner class


name is Ashu
Id is 101

Kotlin Constructor
In Kotlin, constructor is a block of code similar to method. Constructor is declared with the same name as the
class followed by parenthesis '()'. Constructor is used to initialize the variables at the time of object creation.

Types of Kotlin constructors


There are two types of constructors in Kotlin:

1. Primary constructor

2. Secondary constructor

There is only one primary constructor in a Kotlin class whereas secondary constructor may be one or more.

Kotlin primary constructor


Primary constructor is used to initialize the class. It is declared at class header. Primary constructor code is
surrounded by parentheses with optional parameter.

Let's see an example of declaration of primary constructor. In the below code, we declare a constructor myClass
with two parameter name and id. Parameter name is only read property whereas id is read and write property.

1. class myClass(valname: String,varid: Int) {

This page by mytechtalk | Kotlin Constructor 178


2. // class body
3. }

When the object of myClasss is created, it initializes name and id with "Ashu" and "101" respectively.

1. class myClass(val name: String, var id: Int) {


2. }
3. fun main(args: Array<String>){
4. val myclass = myClass ("Ashu", 101)
5.
6. println("Name = ${ myclass.name}")
7. println("Id = ${ myclass.id}")
8. }

Output:

Name = Ashu
Id = 101

Primary constructor with initializer block


The primary constructor does not contain any code. Initializer blocks are used to initialization of code. This block
is prefixed with init keyword. At the period of instance initialization, the initialized blocks are executed in the
same order as they appear in class body.

Let's rewrite the above code using initialize block:

1. class myClass(name: String, id: Int) {


2. val e_name: String
3. var e_id: Int
4. init{
5. e_name = name.capitalize()
6. e_id = id
7.
8. println("Name = ${e_name}")
9. println("Id = ${e_id}")
10. }
11. }
12. fun main(args: Array<String>){
13. val myclass = myClass ("Ashu", 101)
14.

This page by mytechtalk | Kotlin Constructor 179


15. }

Output:

Name = Ashu
Id = 101

In above code, parameters name and id accept values "Ashu" and "101" when myclass object is created. The
properties name and id are used without "val" or "var", so they are not properties of myClass class.

When object of myClass class is created, it executes initializer block which initializese_name and e_id.

Kotlin secondary constructor


In Kotlin, secondary constructor can be created one or more in class. The secondary constructor is created using
"constructor" keyword.

Let's see an example of declaration of secondary constructor. In the below code, we declare two constructor of
myClass with two parameter name and id.

1. class myClass{
2.
3. constructor(id: Int){
4. //code
5. }
6. constructor(name: String, id: Int){
7. //code
8. }
9. }

Let's see an example of secondary constructor assigning the value while object of class is created.

1. class myClass{
2.
3. constructor(name: String, id: Int){
4. println("Name = ${name}")
5. println("Id = ${id}")
6. }
7. }
8. fun main(args: Array<String>){
9. val myclass = myClass ("Ashu", 101)
10.

This page by mytechtalk | Kotlin Constructor 180


11. }

Output:

Name = Ashu
Id = 101

We can also use both primary as well as secondary constructor in a same class. By using primary as well
secondary constructor in same class, secondary constructor needs to authorize to primary constructor.
Authorization to another constructor in same class is done using this() keyword.

For example:

1. class myClass(password: String){


2.
3. constructor(name: String, id: Int, password: String): this(password){
4. println("Name = ${name}")
5. println("Id = ${id}")
6. println("Password = ${password}")
7. }
8. }
9. fun main(args: Array<String>){
10. val myclass = myClass ("Ashu", 101, "mypassword")
11.
12. }

Output:

Name = Ashu
Id = 101
Password = mypassword

Calling one secondary constructor from another


secondary constructor of same class
In Kotlin, one secondary constructor can call another secondary constructor of same class. This is done by
using this() keyword.

For example:

1. class myClass{
2.
3. constructor(name: String, id: Int): this(name,id, "mypassword"){
4. println("this executes next")
This page by mytechtalk | Kotlin Constructor 181
5. println("Name = ${name}")
6. println("Id = ${id}")
7. }
8.
9. constructor(name: String, id: Int,pass: String){
10. println("this executes first")
11. println("Name = ${name}")
12. println("Id = ${id}")
13. println("Password = ${pass}")
14. }
15. }
16. fun main(args: Array<String>){
17. val myclass = myClass ("Ashu", 101)
18.
19. }

Output:

this executes first


Name = Ashu
Id = 101
Password = mypassword
this executes next
Name = Ashu
Id = 101

Calling supper class secondary constructor from derived


class secondary constructor
In Kotlin, one derived class secondary constructor can call the base class secondary constructor. This is done
using super keyword, this is the concept of inheritance.

1. open class Parent{


2.
3. constructor(name: String, id: Int){
4. println("this executes first")
5. println("Name = ${name}")
6. println("Id = ${id}")
7. }
8.
9. constructor(name: String, id: Int,pass: String){

This page by mytechtalk | Kotlin Constructor 182


10. println("this executes third")
11. println("Name = ${name}")
12. println("Id = ${id}")
13. println("Password = ${pass}")
14. }
15. }
16. class Child: Parent{
17. constructor(name: String, id: Int): super(name,id){
18. println("this executes second")
19. println("Name = ${name}")
20. println("Id = ${id}")
21. }
22.
23. constructor(name: String, id: Int,pass: String):super(name,id,"password"){
24. println("this executes forth")
25. println("Name = ${name}")
26. println("Id = ${id}")
27. println("Password = ${pass}")
28. }
29. }
30. fun main(args: Array<String>){
31. val obj1 = Child("Ashu", 101)
32. val obj2 = Child("Ashu", 101,"mypassword")
33. }

Output:

this executes first


Name = Ashu
Id = 101
this executes second
Name = Ashu
Id = 101
this executes third
Name = Ashu
Id = 101
Password = password
this executes forth
Name = Ashu
Id = 101
Password = mypassword

Kotlin Visibility Modifier


This page by mytechtalk | Kotlin Visibility Modifier 183
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.

1. public class Example{


2. }
3. class Demo{
4. }
5. public fun hello()
6. fun demo()
7. public val x = 5
8. val y = 10

All public declaration can be placed at top of the file. If a member of class is not specified then it is by default
public.

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.

1. open class Base{


2. protected val i = 0
3. }
4.
5. class Derived : Base(){
6.
7. fun getValue() : Int
8. {

This page by mytechtalk | Kotlin Visibility Modifier 184


9. return i
10. }
11. }

In Kotlin, protected modifier cannot be declared at top level.

Overriding of protected types


1. open class Base{
2. open protected val i = 5
3. }
4. class Another : Base(){
5. fun getValue() : Int
6. {
7. return i
8. }
9. override val i =10
10. }

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.

1. internal class Example{


2. internal val x = 5
3. internal fun getValue(){
4.
5. }
6. }
7. internal val y = 10

In above, all the fields are declared as internal which are accessible only inside the module in which they are
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.

This page by mytechtalk | Kotlin Visibility Modifier 185


1. private class Example {
2. private val x = 1
3. private valdoSomething() {
4. }
5. }

In above class Example,val x and function doSomthing() are declared as private. The class "Example" is
accessible from the same source file, "val x" and "fun doSomthing()" are accessible within Example class.

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
val derived = Derived()
// derived.c is not visible
}

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

This page by mytechtalk | Kotlin Inheritance 186


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)

1. open class Base(p: Int){


2.
3. }
4. class Derived(p: Int) : Base(p){
5.
6. }

Suppose that,we have two different classes "Programmer" and "Salesman" having the common properties
'name','age', and 'salary' as well as their own separate functionalitiesdoProgram() and fieldWork(). The feature of
inheritance allows that we can inherit (Employee) containing the common features.

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


// code of employee
}

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


// code of programmer
}

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


// code of salesman
}

All Kotlin classes have a common superclass "Any". It is a default superclass for a class with no supertypes
explicitly specified.

For example, a class Example is implicitly inherited from Any.

1. class Example

This page by mytechtalk | Kotlin Inheritance 187


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:

1. open class Example{


2. // I can now be extended!
3. }

Kotlin Inheriting fields from a class


When we inherit a class to derive class, all the fields and functionalities are inherited. We can use these fields
and functionalities in derived class.

For example:

open class Base{


val x = 10
}
class Derived: Base() {
fun foo() {
println("x is equal to " + x)
}
}
fun main(args: Array<String>) {
val derived = Derived()
derived.foo()
}

Output:

x is equal to 10

Kotlin Inheriting methods from a class


1. open class Bird {
2. fun fly() {
3. println("flying...")
4. }
5. }

This page by mytechtalk | Kotlin Inheritance 188


6. class Duck: Bird() {
7. fun swim() {
8. println("swimming...")
9. }
10. }
11. fun main(args: Array<String>) {
12. val duck = Duck()
13. duck.fly()
14. duck.swim()
15. }

Output:

flying...
swimming...

Kotlin Inheritance Example


Here, we declare a class Employee is superclass and Programmer and Salesman are their subclasses. The
subclasses inherit properties name, age and salary as well as subclasses containtheir own functionalitieslike
doProgram() and fieldWork().

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


2. init {
3. println("Name is $name.")
4. println("Age is $age")
5. println("Salary is $salary")
6. }
7. }
8. class Programmer(name: String, age: Int, salary: Float):Employee(name,age,salary){
9. fun doProgram() {
10. println("programming is my passion.")
11. }
12. }
13. class Salesman(name: String, age: Int, salary: Float):Employee(name,age,salary){
14. fun fieldWork() {
15. println("travelling is my hobby.")
16. }
17. }
18. fun main(args: Array<String>){

This page by mytechtalk | Kotlin Inheritance 189


19. val obj1 = Programmer("Ashu", 25, 40000f)
20. obj1.doProgram()
21. val obj2 = Salesman("Ajay", 24, 30000f)
22. obj2.fieldWork()
23. }

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.

Kotlin Inheritance and primary constructor


If the base and derived class both having primary constructor in that case the parameters are initialized in the
primary constructor of base class. In above example of inheritance, all classes contain three parameters "name",
"age" and "salary" and all these parameters are initialized in primary constructor of base class.

When a base and derived class both contains different numbers of parameters in their primary constructor then
base class parameters are initialized form derived class object.

For example:

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


init {
println("Name is $name.")
println("Salary is $salary")
}
}
class Programmer(name: String, dept: String, salary: Float):Employee(name,salary){
init {
println("Name $name of department $dept with salary $salary.")
}
fun doProgram() {
println("Programming is my passion.")

}
}
class Salesman(name: String, dept: String, salary: Float):Employee(name,salary){
This page by mytechtalk | Kotlin Inheritance 190
init {
println("Name $name of department $dept with salary $salary.")
}
fun fieldWork() {
println("Travelling is my hobby.")

}
}
fun main(args: Array<String>){
val obj1 = Programmer("Ashu", "Development", 40000f)
obj1.doProgram()
println()
val obj2 = Salesman("Ajay", "Marketing", 30000f)
obj2.fieldWork()
}

Output:

Name is Ashu.
Salary is 40000.0
Name Ashu of department Development with salary 40000.0.
Programming is my passion.

Name is Ajay.
Salary is 30000.0
Name Ajay of department Marketing with salary 30000.0.
Travelling is my hobby.

When an object of derived class is created, it calls its superclass first and executes init block of base class
followed by its own.

Kotlin Inheritance and secondary constructor


If derived class does not contain any primary constructor then it is required to call the base class secondary
constructor from derived class using super keyword.

For example,

open class Patent {

constructor(name: String, id: Int) {


println("execute super constructor $name: $id")
}

This page by mytechtalk | Kotlin Inheritance 191


}

class Child: Patent {

constructor(name: String, id: Int, dept: String): super(name, id) {


print("execute child class constructor with property $name, $id, $dept")
}
}
fun main(args: Array<String>) {
val child = Child("Ashu",101, "Developer")
}

Output:

execute super constructor Ashu: 101


execute child class constructor with property Ashu, 101, Developer

In above example, when object of Child class is created, it calls its constructor and initializes its parameters with
values "Ashu", "101" and "Developer". At the same time Child class constructor calling its supper class
constructor using super keyword with values of name and id. Due to the presence of super keyword thebody of
superclass constructor executes first and returns to Child class constructor.

Kotlin Method Overriding


Method overriding means providing the specific implementation of method of super (parent) class into its
subclass (child) class.

In other words, when subclass redefines or modifies the method of its superclass into subclass, it is known as
method overriding. Method overriding is only possible in inheritance.

KotlinRules of method overriding

o Parent class and its method or property which is to be overridden must be open (non-final).

o Method name of base class and derived class must have same.

o Method must have same parameter as in base class.

Example of inheritance without overriding


open class Bird {
open fun fly() {
println("Bird is flying...")
}
}

This page by mytechtalk | Kotlin Inheritance 192


class Parrot: Bird() {

}
class Duck: Bird() {

}
fun main(args: Array<String>) {
val p = Parrot()
p.fly()
val d = Duck()
d.fly()
}

Output:

Bird is flying...
Bird is flying...

In above example, a program without overriding the method of base class we found that both derived classes
Parrot and Duck perform the same common operation. To overcome with this problem we use the concept of
method overriding.

Example of Kotlin method overriding


In this example, the method fly() of parent class Bird is overridden in its subclass Parrot and Duck. To override
the method of parent class, the parent class and its method which is going to override must be declare as open. At
the same time method which is overridden in child class must be prefaced with keyword override.

1. open class Bird {


2. open fun fly() {
3. println("Bird is flying...")
4. }
5. }
6. class Parrot: Bird() {
7. override fun fly() {
8. println("Parrot is flying...")
9. }
10. }
11. class Duck: Bird() {
12. override fun fly() {
13. println("Duck is flying...")

This page by mytechtalk | Kotlin Inheritance 193


14. }
15. }
16. fun main(args: Array<String>) {
17. val p = Parrot()
18. p.fly()
19. val d = Duck()
20. d.fly()
21. }

Output:

Parrot is flying...
Duck is flying...

Example of Kotlin property overriding


Property of superclass can also be overridden in its subclass as similar to method. A color property of Bird class
is overridden in its subclass Parrot and Duck and modified.

1. open class Bird {


2. open var color = "Black"
3. open fun fly() {
4. println("Bird is flying...")
5. }
6. }
7. class Parrot: Bird() {
8. override var color = "Green"
9. override fun fly() {
10. println("Parrot is flying...")
11. }
12. }
13. class Duck: Bird() {
14. override var color = "White"
15. override fun fly() {
16. println("Duck is flying...")
17. }
18. }
19. fun main(args: Array<String>) {
20. val p = Parrot()
21. p.fly()
This page by mytechtalk | Kotlin Inheritance 194
22. println(p.color)
23. val d = Duck()
24. d.fly()
25. println(d.color)
26. }

Output:

Parrot is flying...
Green
Duck is flying...
White

We can override the val property with var property in inheritance but vice-versa is not true.

Kotlin superclass implementation


Derived class can also call its superclass methods and property using super keyword.

For example:

1. open class Bird {


2. open var color = "Black"
3. open fun fly() {
4. println("Bird is flying...")
5. }
6. }
7. class Parrot: Bird() {
8. override var color = "Green"
9. override fun fly() {
10. super.fly()
11. println("Parrot is flying...")
12.
13. }
14. }
15.
16. fun main(args: Array<String>) {
17. val p = Parrot()
18. p.fly()
19. println(p.color)
20.

This page by mytechtalk | Kotlin Inheritance 195


21. }

Output:

Bird is flying...
Parrot is flying...
Green

Kotlin multiple class implementation


In Kotlin, derived class uses a supertype name in angle brackets, e.gsuper<Base> when it implements same
function name provided in multiple classes.

For example, a derived class Parrotextends its superclass Bird and implement Duck interface containing same
function fly(). To call particular method of each class and interface we must be mention supertype name in angle
brackets as super<Bird>.fly() and super<Duck>.fly() for each method.

1. open class Bird {


2. open var color = "Black"
3. open fun fly() {
4. println("Bird is flying...")
5. }
6. }
7. interface Duck {
8. fun fly() {
9. println("Duck is flying...")
10. }
11. }
12. class Parrot: Bird(),Duck {
13. override var color = "Green"
14. override fun fly() {
15. super<Bird>.fly()
16. super<Duck>.fly()
17. println("Parrot is flying...")
18.
19. }
20. }
21. fun main(args: Array<String>) {
22. val p = Parrot()
23. p.fly()
24. println(p.color)

This page by mytechtalk | Kotlin Inheritance 196


25.
26. }

Output:

Bird is flying...
Duck is flying...
Parrot is flying...

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


1. abstract class A {
2. var x = 0
3. abstract fun doSomething()
4. }

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 of abstract class that has abstract method


In this example, there is an abstract class Car that contains an abstract function run(). The implementation of
run() function is provided by its subclass Honda.

1. abstract class Car{


2. abstract fun run()
3. }
4. class Honda: Car(){
5. override fun run(){
6. println("Honda is running safely..")
7. }
8. }
9. fun main(args: Array<String>){

This page by mytechtalk | Kotlin Abstract class 197


10. val obj = Honda()
11. obj.run();
12. }

Output:

Honda is running safely..

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

1. open class Car {


2. open fun run() {
3. println("Car is running..")
4. }
5. }
6. abstract class Honda : Car() {
7. override abstract fun run()
8. }
9. class City: Honda(){
10. override fun run() {
11. // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
12. println("Honda City is running..")
13. }
14. }
15. fun main(args: Array<String>){
16. val car = Car()
17. car.run()
18. val city = City()
19. city.run()
20. }

Output:

Car is running..
Honda City is running..

In above example, An abstract class Honda extends the class Car and its function run(). Honda class override
the run() function of Car class. The Honda class did not give the implementation of run() function as it is also
declared as abstract. The implementation of abstract function run() of Honda class is provided by City class.

This page by mytechtalk | Kotlin Abstract class 198


Example of real scenario of abstract class
In this example, an abstract class Bank that contains an abstract function simpleInterest() accepts three
parameters p,r,and t. The class SBI and PNB provides the implementation of simpleInterest() function and returns
the result.

1. abstract class Bank {


2. abstract fun simpleInterest(p: Int, r: Double, t: Int) :Double
3. }
4.
5. class SBI : Bank() {
6. override fun simpleInterest(p: Int, r: Double, t: Int): Double{
7. return (p*r*t)/100
8. }
9. }
10. class PNB : Bank() {
11. override fun simpleInterest(p: Int, r: Double, t: Int): Double{
12. return (p*r*t)/100
13. }
14. }
15. fun main(args: Array<String>) {
16. var sbi: Bank = SBI()
17. val sbiint = sbi.simpleInterest(1000,5.0,3)
18. println("SBI interest is $sbiint")
19. var pnb: Bank = PNB()
20. val pnbint = pnb.simpleInterest(1000,4.5,3)
21. println("PNB interest is $pnbint")
22. }

Output:

SBI interest is 150.0


PNB interest is 135.0

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.

This page by mytechtalk | Kotlin Interface 199


Defining Interface
An interface is defined using the keyword interface. For example:

1. interface MyInterface {
2. val id: Int // abstract property
3. fun absMethod()// abstract method
4. fun doSomthing() {
5. // optional body
6. }
7. }

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.

Subclass extends only one super class but implements multiple interfaces. Extension of parent class or interface
implementation are done using (:) operator in their subclass.

Implementing Interfaces
In this example, we are implementing the interface MyInterface in InterfaceImp class. InterfaceImp class
provides the implementation of property id and abstract method absMethod() declared in MyInterface interface.

1. interface MyInterface {
2. var id: Int // abstract property
3. fun absMethod():String // abstract method
4. fun doSomthing() {
5. println("MyInterface doing some work")
6. }
7. }
8. class InterfaceImp : MyInterface {
9. override var id: Int = 101
10. override fun absMethod(): String{
This page by mytechtalk | Kotlin Interface 200
11. return "Implementing abstract method.."
12. }
13. }
14. fun main(args: Array<String>) {
15. val obj = InterfaceImp()
16. println("Calling overriding id value = ${obj.id}")
17. obj.doSomthing()
18. println(obj.absMethod())
19. }

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.

1. interface MyInterface1 {
2. fun doSomthing()
3. }
4. interface MyInterface2 {
5. fun absMethod()
6. }
7. class MyClass : MyInterface1, MyInterface2 {
8. override fun doSomthing() {
9. println("overriding doSomthing() of MyInterface1")
10. }
11.
12. override fun absMethod() {
13. println("overriding absMethod() of MyInterface2")
14. }
15. }
16. fun main(args: Array<String>) {

This page by mytechtalk | Kotlin Interface 201


17. val myClass = MyClass()
18. myClass.doSomthing()
19. myClass.absMethod()
20. }

Output:

overriding doSomthing() of MyInterface1


overriding absMethod() of MyInterface2

Resolving different Interfaces having same method


overriding conflicts
Let's see an example in which interface MyInterface1 and interface MyInterface2 both contains same non-
abstract method. A class MyClass provides the implementation of these interfaces. Calling the method of
interface using object of MyClass generates an error.

1. interface MyInterface1 {
2. fun doSomthing(){
3. println("overriding doSomthing() of MyInterface1")
4. }
5. }
6. interface MyInterface2 {
7. fun doSomthing(){
8. println("overriding doSomthing() of MyInterface2")
9. }
10. }
11. class MyClass : MyInterface1, MyInterface2 {
12.
13. }
14. fun main(args: Array<String>) {
15. val myClass = MyClass()
16. myClass.doSomthing()
17. }

Output:

Kotlin: Class 'MyClass' must override public open fun doSomthing(): Unit defined in MyInterface1 because it
inherits multiple interface methods of it

To solve the above problem we need to specify particular method of interface which we are calling. Let's see an
example below.
This page by mytechtalk | Kotlin Interface 202
In below example, two interfaces MyInterface1 and MyInterface2 contain two
abstract methodsadsMethod() and absMethod(name: String) and non-abstract method doSomthing() in both
respectively. A class MyClass implements both interface and override abstract
method absMethod() and absMethod(name: String) . To override the non-abstract method doSomthing() we need
to specify interface name with method using super keyword as super<interface_name>.methodName().

1. interface MyInterface1 {
2. fun doSomthing() {
3. println("MyInterface 1 doing some work")
4. }
5. fun absMethod()
6. }
7. interface MyInterface2 {
8. fun doSomthing(){
9. println("MyInterface 2 doing some work")
10. }
11. fun absMethod(name: String)
12. }
13. class MyClass : MyInterface1, MyInterface2 {
14. override fun doSomthing() {
15. super<MyInterface2>.doSomthing()
16. }
17.
18. override fun absMethod() {
19. println("Implements absMethod() of MyInterface1")
20. }
21. override fun absMethod(n: String) {
22. println("Implements absMethod(name) of MyInterface2 name is $n")
23. }
24. }
25. fun main(args: Array<String>) {
26. val myClass = MyClass()
27. myClass.doSomthing()
28. myClass.absMethod()
29. myClass.absMethod("Ashu")
30. }

Output:

This page by mytechtalk | Kotlin Interface 203


MyInterface 2 doing some work
Implements absMethod() of MyInterface1
Implements absMethod(name) of MyInterface2 name is Ashu
interface MyInterface1 {
fun doSomthing() {
println("MyInterface 1 doing some work")
}
fun absMethod()
}

interface MyInterface2 {
fun doSomthing() {
println("MyInterface 2 doing some work")
}
fun absMethod() {
println("MyInterface 2 absMethod")
}

class C : MyInterface1 {
override fun absMethod() {
println("MyInterface1 absMethod implementation")
}
}

class D : MyInterface1, MyInterface2 {


override fun doSomthing() {
super<MyInterface1>.doSomthing()
super<MyInterface2>.doSomthing()
}

override fun absMethod() {

super<MyInterface2>.absMethod()
}
}

fun main(args: Array<String>) {


val d = D()
val c = C()
d.doSomthing()
d.absMethod()
c.doSomthing()
c.absMethod()
}

Output:

MyInterface 1 doing some work


MyInterface 2 doing some work
MyInterface 2 absMethod
MyInterface 1 doing some work
MyInterface1 absMethod implementation

Kotlin Data class


This page by mytechtalk | Kotlin Data class 204
Data class is a simple class which is used to hold data/state and contains standard functionality. A data keyword
is used to declare a class as a data class.

1. data class User(val name: String, val age: Int)

Declaring a data class must contains at least one primary constructor with property argument (val or var).

Data class internally contains the following functions:

o equals(): Boolean

o hashCode(): Int

o toString(): String

o component() functions corresponding to the properties

o copy()

Due to presence of above functions internally in data class, the data class eliminates the boilerplate code.

A compression between Java data class and Kotlin data class


If we want to create a User entry in Java using data class, it require lots of boilerplate code.

1. import java.util.Objects;
2.
3. public class User {
4. private String name;
5. private int id;
6. private String email;
7.
8. public User(String name, int id, String email) {
9. this.name = name;
10. this.id = id;
11. this.email = email;
12. }
13.
14. public String getName() {
15. return name;
16. }
17.
18. public void setName(String name) {

This page by mytechtalk | Kotlin Data class 205


19. this.name = name;
20. }
21.
22. public intgetId() {
23. return id;
24. }
25.
26. public void setId(int id) {
27. this.id = id;
28. }
29.
30. public String getEmail() {
31. return email;
32. }
33.
34. public void setEmail(String email) {
35. this.email = email;
36. }
37.
38. @Override
39. public boolean equals(Object o) {
40. if (this == o) return true;
41. if (!(o instanceof User)) return false;
42. User user = (User) o;
43. return getId() == user.getId() &&
44. Objects.equals(getName(), user.getName()) &&
45. Objects.equals(getEmail(), user.getEmail());
46. }
47.
48. @Override
49. public inthashCode() {
50.
51. return Objects.hash(getName(), getId(), getEmail());
52. }
53.
54. @Override

This page by mytechtalk | Kotlin Data class 206


55. public String toString() {
56. return "User{" +
57. "name='" + name + '\'' +
58. ", id=" + id +
59. ", email='" + email + '\'' +
60. '}';
61. }
62. }

Calling the constructor of above Java data class using the object of User class as

1. class MyClass{
2. public static void main(String agrs[]){
3. User u = new User("Ashu",101,"mymail@mail.com");
4. System.out.println(u);
5. }
6. }

Output:

User{name='Ashu', id=101, email='mymail@mail.com'}

The above Java data class code is rewritten in Kotlin data code in single line as

1. data class User(var name: String, var id: Int, var email: String)

Calling the constructor of above Kotlin data class using the object of User class as

1. fun main(agrs: Array<String>) {


2. val u = User("Ashu", 101, "mymail@mail.com")
3. println(u)
4. }

Output:

User(name=Ashu, id=101, email=mymail@mail.com)

Requirements of data class


In order to create a data class, we need to fulfill the following requirements:

o Contain primary constructor with at least one parameter.

This page by mytechtalk | Kotlin Data class 207


o Parameters of primary constructor marked as val or var.

o Data class cannot be abstract, inner, open or sealed.

o Before 1.1,data class may only implements interface. After that data classes may extend other classes.

Kotlin data class toString() methods


Kotlin data class only focuses on data rather than code implementation.

Let's see a simple program without data class. In this class, we are trying to print the reference of Product class
using its object.

1. class Product(varitem: String, var price: Int)


2.
3. fun main(agrs: Array<String>) {
4. val p = Product("laptop", 25000)
5. println(p)
6. }

While printing the reference of Product class, it displays the hashCode() with class name of Product. It does not
print the data.

Output:

Product@266474c2

The above program is rewritten using data class and printing the reference of Product class and displaying the
data of object. It happens because the data class internally contains the toString() which display the string
representation of object .

1. data class Product(varitem: String, var price: Int)


2.
3. fun main(agrs: Array<String>) {
4. val p = Product("laptop", 25000)
5. println(p)
6. }

Output:

Product(name=laptop, price=25000)

Kotlin data classequals() and hashCode()


The equal() method is used to check other object is "equal to" current object. While doing comparison between
two or more hashCode(), equals() method returns true if the hashCode() are equal, else it returns a false.

This page by mytechtalk | Kotlin Data class 208


For example, let's see an example in which a normal class comparing the two references of same class Product
having same data.

1. class Product(varitem: String, var price: Int)


2.
3. fun main(agrs: Array<String>) {
4. val p1 = Product("laptop", 25000)
5. val p2 = Product("laptop", 25000)
6. println(p1==p2)
7. println(p1.equals(p2))
8. }

In above program, reference p1 and reference p2 has different references. Due to different reference values in p1
and p2, doing comparison displays false.

Output:

false
false

The above program is rewritten using data class, printing the reference of Product class and displaying the data
of object.

The hashCode() method returns hash code for the object. The hashCode() produce same integer result, if two
objects are equal.

1. data class Product(varitem: String, var price: Int)


2.
3. fun main(agrs: Array<String>) {
4. val p1 = Product("laptop", 25000)
5. val p2 = Product("laptop", 25000)
6. println(p1==p2)
7. println(p1.equals(p2))
8. }

Output:

true
true

Kotlin data class copy() method


The data class provides a copy() method which is used to create a copy (or colon) of object. Using copy()
method, some or all properties of object can be altered.

This page by mytechtalk | Kotlin Data class 209


For example:

1. data class Product(var item: String, var price: Int)


2.
3. fun main(agrs: Array<String>) {
4. val p1 = Product("laptop", 25000)
5. println("p1 object contain data : $p1")
6. val p2 = p1.copy()
7. println("p2 copied object contains default data of p1: $p2")
8. val p3 = p1.copy(price = 20000)
9. println("p3 contain altered data of p1 : $p3")
10. }

Output:

p1 object contain data : Product(item=laptop, price=25000)


p2 copied object contains default data of p1: Product(item=laptop, price=25000)
p3 contain altered data of p1 : Product(item=laptop, price=20000)

Default and named arguments in data class


We can also assign the default arguments in primary constructor of data class. These default values can be
changed later on program if required.

For example:

1. data class Product(var item: String = "laptop", var price: Int = 25000)
2.
3. fun main(agrs: Array<String>) {
4. val p1 = Product(price = 20000)
5. println(p1)
6. }

Output:

Product(item=laptop, price=20000)

Kotlin Sealed Class


Sealed class is a class which restricts the class hierarchy. A class can be declared as sealed class using "sealed"
keyword before the class name. It is used to represent restricted class hierarchy.

Sealed class is used when the object have one of the types from limited set, but cannot have any other type.

This page by mytechtalk | Kotlin Sealed Class 210


The constructors of sealed classes are private in default and cannot be allowed as non-private.

Declaration of sealed class


1. sealed class MyClass

The subclasses of sealed classes must be declared in the same file in which sealed class itself.

1. sealed class Shape{


2. class Circle(var radius: Float): Shape()
3. class Square(var length: Int): Shape()
4. class Rectangle(var length: Int, var breadth: Int): Shape()
5. object NotAShape : Shape()
6. }

Sealed class ensures the important of type-safety by restricting the set of types at compile time only.

1. sealed class A{
2. class B : A()
3. {
4. class E : A() //this works.
5. }
6. class C : A()
7. init {
8. println("sealed class A")
9. }
10. }
11.
12. class D : A() //this works
13. {
14. class F: A() //This won't work,because sealed class is defined in another scope.
15. }

A sealed class is implicitly an abstract class which cannot be instantiated.

1. sealed class MyClass


2. fun main(args: Array<String>)
3. {
4. var myClass = MyClass() //compiler error. sealed types cannot be instantiated.
5. }

This page by mytechtalk | Kotlin Sealed Class 211


Sealed class with when
Sealed classes are commonly used with when expression. As the sub classes of sealed classes have their own
types act as a case. Due to this, when expression in sealed class covers all the cases and avoid to add else clause.

For example:

1. sealed class Shape{


2. class Circle(var radius: Float): Shape()
3. class Square(var length: Int): Shape()
4. class Rectangle(var length: Int, var breadth: Int): Shape()
5. // object NotAShape : Shape()
6. }
7.
8. fun eval(e: Shape) =
9. when (e) {
10. is Shape.Circle ->println("Circle area is ${3.14*e.radius*e.radius}")
11. is Shape.Square ->println("Square area is ${e.length*e.length}")
12. is Shape.Rectangle ->println("Rectagle area is ${e.length*e.breadth}")
13. //else -> "else case is not require as all case is covered above"
14. // Shape.NotAShape ->Double.NaN
15. }
16. fun main(args: Array<String>) {
17.
18. var circle = Shape.Circle(5.0f)
19. var square = Shape.Square(5)
20. var rectangle = Shape.Rectangle(4,5)
21.
22. eval(circle)
23. eval(square)
24. eval(rectangle)
25. }

Output:

Circle area is 78.5


Square area is 25
Rectagle area is 20

Kotlin Extension Function


This page by mytechtalk | Kotlin Extension Function 212
Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any
type of design pattern. The created extension functions are used as a regular function inside that class.

The extension function is declared with a prefix receiver type with method name.

1. fun <class_name>.<method_name>()

In the above declaration, <class_name> is a receiver type and the <method_name>() is an extension function.

Example of extension function declaration and its use


In general, we call all methods from outside the class which are already defined inside the class.In below
example, a Student class declares a method is Passed() which is called from main() function by creating the
object student of Student class.

Suppose that we want to call a method (say isExcellent()) of Student class which is not defined in class. In such
situation, we create a function (isExcellent()) outside the Student class as Student.isExcellent() and call it from
the main() function. The declare Student.isExcellent() function is known as extension function, where Student
class is known as receiver type.

1. class Student{
2. fun isPassed(mark: Int): Boolean{
3. return mark>40
4. }
5. }
6. fun Student.isExcellent(mark: Int): Boolean{
7. return mark > 90
8. }
9. fun main(args: Array<String>){
10. val student = Student()
11. val passingStatus = student.isPassed(55)
12. println("student passing status is $passingStatus")
13.
14. val excellentStatus = student.isExcellent(95)
15. println("student excellent status is $excellentStatus")
16. }

Output:

student passing status is true


student excellent status is true

The above example only demonstrates about how to declare an extension function.

This page by mytechtalk | Kotlin Extension Function 213


Kotlin extension function example
Let's see the real example of extension function. In this example, we are swapping the elements of
MutableList<> using swap() method. However, MutableList<>class does not provide the swap() method
internally which swap the elements of it. For doing this we create an extension function for MutableList<> with
swap() function.

The list object call the extension function (MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int>)
using list.swap(0,2) function call. The swap(0,2) function pass the index value of list inside
MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int>) sxtension function.

1. fun MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int> {


2. val tmp = this[index1] // 'this' represents to the list
3. this[index1] = this[index2]
4. this[index2] = tmp
5. return this
6. }
7. fun main(args: Array<String>) {
8. val list = mutableListOf(5,10,15)
9. println("before swapping the list :$list")
10. val result = list.swap(0, 2)
11. println("after swapping the list :$result")
12. }

Output:

before swapping the list :[5, 10, 15]


after swapping the list :[15, 10, 5]

Extension Function as Nullable Receiver


The extension function can be defined as nullable receiver type. This nullable extension function is called
through object variable even the object value is null. The nullability of object is checked using this ==
null inside the body.

Let's rewrite the above program using extension function as nullable receiver.

1. funMutableList<Int>?.swap(index1: Int, index2: Int): Any {


2. if (this == null) return "null"
3. else {
4. val tmp = this[index1] // 'this' represents to the list
5. this[index1] = this[index2]
6. this[index2] = tmp

This page by mytechtalk | Kotlin Extension Function 214


7. return this
8. }
9. }
10. fun main(args: Array<String>) {
11. val list = mutableListOf(5,10,15)
12. println("before swapping the list :$list")
13. val result = list.swap(0, 2)
14. println("after swapping the list :$result")
15. }

Output:

before swapping the list :[5, 10, 15]


after swapping the list :[15, 10, 5]

Companion Object Extensions


A companion object is an object which is declared inside a class and marked with the companion keyword.
Companion object is used to call the member function of class directly using the class name (like static in java).

A class which contains companion object can also be defined as extension function and property for the
companion object.

Example of companion object


In this example, we call a create() function declared inside companion object using class name (MyClass) as
qualifier.

1. class MyClass {
2. companion object {
3. fun create():String{
4. return "calls create method of companion object"
5. }
6. }
7. }
8. fun main(args: Array<String>){
9. val instance = MyClass.create()
10. }

Output:

calls create method of companion object

This page by mytechtalk | Kotlin Extension Function 215


Companion object extensions example
Let's see an example of companion object extensions. The companion object extension is also being called using
the class name as the qualifier.

1. class MyClass {
2. companion object {
3. fun create(): String {
4. return "calling create method of companion object"
5. }
6. }
7. }
8. fun MyClass.Companion.helloWorld() {
9. println("executing extension of companion object")
10. }
11. fun main(args: Array<String>) {
12. MyClass.helloWorld() //extension function declared upon the companion object
13. }

Output:

executing extension of companion object

Kotlin Generics
Generics are the powerful features that allow to define classes, methods, and properties etc. which can be
accessed using different types. The type differences of classes, methods, etc. are checked at compile-time.

The generic type class or method is declared as parameterized type. A parameterized type is an instance of
generic type with actual type arguments. The parameterized types are declared using angle brackets <> Generics
are mostly used in collections.

Advantage of Generics
Following are the key advantages of using generics:

o Type-safety: Generic allows to hold only single type of object. Generic does not allow to store other object.

o Type casting is not required: There is no need to typecast the object.

o Compile time checking: Generics code is checked at compile time so that it can avoid any problems at runtime.

Let's see a problem without using the generics.

This page by mytechtalk | Kotlin Generics 216


In this example, we create a Person class with primary constructor having single parameter. Now, we want to
pass the different type of data in object of Person class (say Int type as Person(30) and String type as
Person("40")). The primary constructor of Person class accept Int type Person(30) and regrets String type
Person("40"). It generates a compile time error as type mismatch.

1. class Person (age:Int){


2. var age: Int = age
3. init {
4. this.age= age
5. println(age)
6. }
7. }
8. fun main(args: Array<String>){
9. var ageInt: Person = Person(30)
10. var ageString: Person = Person("30")// compile time error
11. }

To solve the above problem, we use a generic type class which is a user defined class that accepts different type
of parametersin single class.

Let's rewrite the above code using generic type. A class Person of type <T> is a general type class that accepts
both Int and String types of parameter.

In other words, the type parameter <T> is a place holder that will be replaced by type argument. It will be
replaced when the generic type is instantiated.

1. class Person<T>(age: T){


2. var age: T = age
3. init {
4. this.age= age
5. println(age)
6. }
7. }
8. fun main(args: Array<String>){
9. var ageInt: Person<Int> = Person<Int>(30)
10. var ageString: Person<String> = Person<String>("40")
11. }

Output:

30
40

This page by mytechtalk | Kotlin Generics 217


In above example, when the object of Person class is created using type Int as Person<Int>(30) and
Person<String>("40"), it replaces the Person class of type T with Int and String respectively.

Syntax of generic class

1. class_or_interface<Type>

Syntax of generic method

1. <Type>methodName(parameter: classType<Type>)

Kotlin generic example


Let's see an example of generic method. In this example, we are accessing the generic method of collection type
(ArrayList). For doing this, we create two different objectsof ArrayList class
arrayListOf<String>("Ashu","Ajay") and arrayListOf<Float>(10.5f,5.0f,25.5f) of String and Float types
respectively. When we call the generic method <T>printValue(list: ArrayList<T>) using printValue(stringList),
the type T of method <T>printValue(list: ArrayList<T>)will be replaced by String type. Similarly, when we call
the generic method using printValue(floatList), the type T of method <T>printValue(list: ArrayList<T>) will
replace by Float type.

1. fun main(args: Array<String>){


2. val stringList: ArrayList<String> = arrayListOf<String>("Ashu","Ajay")
3. val s: String = stringList[0]
4. println("printing the string value of stringList: $s")
5. printValue(stringList)
6. val floatList: ArrayList<Float> = arrayListOf<Float>(10.5f,5.0f,25.5f)
7. printValue(floatList)
8. }
9. fun <T>printValue(list: ArrayList<T>){
10. for(element in list){
11. println(element)
12. }
13. }

Output:

printing the string value of stringList: Ashu


Ashu
Ajay
10.5
5.0
25.5

This page by mytechtalk | Kotlin Generics 218


Kotlin generic extension function example
As extension function allows to add methods to class without inherit a class or any design pattern.

In this example, we add a method printValue()to ArrayList class of generic type. This method is called form
stringList.printValue() and floatList.printValue()of String and Float types respectively. As "this" keyword in
extension function represent the current calling instance. When we call the extension function using
stringList.printValue(), the this represents stringList instance containing String type values. Similarly, calling the
extension function using floatList.printValue(), the this represents floatList instance containing Float type values.

1. fun main(args: Array<String>){


2. val stringList: ArrayList<String> = arrayListOf<String>("Ashu","Ajay")
3. stringList.printValue()
4. val floatList: ArrayList<Float> = arrayListOf<Float>(10.5f,5.0f,25.5f)
5. floatList.printValue()
6. }
7. fun <T>ArrayList<T>.printValue(){
8. for(element in this){
9. println(element)
10. }
11. }

Output:

Ashu
Ajay
10.5
5.0
25.5

Kotlin Ranges
Kotlin range is defined as an interval from start value to the end value. Range expressions are created with
operator (. .) which is complemented by in and !in. The value which is equal or greater than start value and
smaller or equal to end value comes inside the defined range.

1. val aToZ = 'a'..'z'


2. val oneToNine = 1..9

While evaluating the above code val aToZ = 'a'..'z'as 'a'in aToZ returns true, 'b' in aToZ returns true and so on.
The code val oneToNine = 1..9 evaluates as 1 in oneToNine returns true, but the evaluation 10 in
oneToNine returns false.

This page by mytechtalk | Kotlin Ranges 219


Integral Type Ranges
Integral type ranges (IntRange, LongRange, CharRange) are the ability to use in for loop. The compiler converts
this integral type in simple analogue of Java's index for-loop.

Example of Kotlin range


1. fun main(args: Array<String>) {
2.
3. for (a in 1..5){
4. print(a )
5. }
6. println()
7. for(x in 'a'..'f'){
8. print(x )
9. }
10. println()
11. val range = 1.0..5.0
12. println(range)
13. println("3.14 in range is ${3.14 in range}")
14. }

Output:

12345
abcdef
1.0..5.0
3.14 in range is true

What happened when we try to iterate a r range in decreasing order using . . operator ? This will print nothing.

for (a in 5..1){
print(a )// print nothing
}

To iterate the element in decreasing order, use the standard library downTo() function or downTo keyword.

1. for (a in 5 downTo 1){


2. print(a )// 54321
3. }

until range
The until() function or until keyword in range is used to exclude the last element. It iterates range from start to 1
less than end.
This page by mytechtalk | Kotlin Ranges 220
1. for (a in 1 until 5){
2. print(a ) // print 1234
3. }

The above range excludes 5 and iterate from 1 to 4.

Kotlin range of integer


Let's see an example of integer range using downTo(), downTo, and rangeTo() methods.

1. fun main(args: Array<String>) {


2. for (x in 1..5)
3. print(x)
4. println()
5. for (x in 5 downTo 1)
6. print(x)
7. println()
8. for (x in 1.rangeTo(5))
9. print(x)
10. println()
11. for (x in 5.downTo(1))
12. print(x)
13. println()
14. }

Output:

12345
54321
12345
54321

Kotlin range of characters


Example of Kotlin ranges using char data types.

1. fun main(args: Array<String>) {


2. (x in 'a'..'e')
3. print("$x ")
4. ntln()
5. for (x in 'e' downTo 'a')

This page by mytechtalk | Kotlin Ranges 221


6. print("$x ")
7. }

Output:

a bcde
edcba

Kotlin range step


Kotlin step keyword in range is used to iterate the range in the interval of given step value (int value).

1. fun main(args: Array<String>) {


2. for (x in 1..10 step 2)
3. print("$x ")
4. println()
5. for (x in 10 downTo 1 step 3)
6. print("$x ")
7. }

Output:

13579
10 7 4 1

Kotlin range iterator


An iterator() method is also be used to iterate the range value. It uses hasNext() method which checks the next
element in the range and next() method returns the next element of the range.

1. fun main(args: Array<String>) {


2.
3. val chars = ('a'..'e')
4. val it = chars.iterator()
5. while (it.hasNext()) {
6. val x = it.next()
7. print("$x ")
8. }
9. }

Output:

abcde

This page by mytechtalk | Kotlin Ranges 222


Working of ranges
Ranges implement ClosedRange<T> a common interface in the library. It represents a closed mathematical
interval defined for comparable types. It contains two endpoints as start and end (endInclusive)points. The
operation performed in range is to check whether the element is contained in it or not. This is done by
using in or !in operators.

An arithmetic progression is represented by integral type progressions such as CharProgression, IntProgression,


Long Progression. Progressions represent the first element, the last element and the step which is non-zero. The
first element is first, sub-sequent elements represent previous element plus step and the last element is the last
element unless progression is completed.

Progression refers to subtype of Iterable<N>, where N is Char, Int or Long. As progression is Iterable<N> type it
can be used in for-loop and function such as filter, map etc.

The . .operator creates an object for integral type which implements both ClosedRange<T> and Progression. For
example, a range type LongRange implements ClosedRange<Int> and extends Long Progression, it means all the
operation which are defined for LongProgression is also available for LongRange. The output generated by
downTo() and step() functions is always a Progression.

The last element of the Progression is largest value not greater than the end value for positive step. The minimum
value of progression is not less than the end value for negative step. The last value is checked by using (last-first)
%step == 0.

Kotlin Utility Functions


Kotlin range utility functions have several standard library functions which are used in Kotlin ranges. These
utility functions are as follow:

This page by mytechtalk | Working of ranges 223


o rangeTo()

o downTo()

o reversed()

o step()

Kotlin rangeTo()
The rangeTo() function is used to return the value from start to end in increasing order mentioned in a range.
The rangeTo()function is integral types which calls the constructors of Range class.

Example of rangeTo() function


1. fun main(args: Array<String>) {
2. var range: IntRange = 1.rangeTo(5)
3. println("Printing value: 1.rangeTo(5)")
4. for (x in range){
5. print("$x ")
6. }
7. println("")
8. var range2: IntRange = IntRange(1,5)
9. println("Printing value: IntRange(1,5)")
10. for (x in range2){
11. print("$x ")
12. }
13. }

Output:

Printing value: 1.rangeTo(5)


12345
Printing value: IntRange(1,5)
12345

The data types (or types) which are floating point like Double, Float are not define in rangeTo operator.

Kotlin downTo()
The downTo() extension function is used to return the value in decreasing order mention from higher order to
lower order. The downTo() function is defined for pair of integral types.

Syntax:

This page by mytechtalk | Kotlin Utility Functions 224


1. fun Long.downTo(other: Int): LongProgression {
2. return LongProgression.fromClosedRange(this, other.toLong(), -1L)
3. }
4.
5. fun Byte.downTo(other: Int): IntProgression {
6. return IntProgression.fromClosedRange(this.toInt(), other, -1)
7. }

Example of downTo() function

1. fun main(args: Array<String>) {


2. println("Range 1")
3. var range1 = 5 downTo 1
4. for (x in range1){
5. print("$x ")
6. }
7. println()
8. println("Range 2")
9. var range2: IntProgression = 5.downTo(1)
10. for (x in range2){
11. print("$x ")
12. }
13. println()
14. println("Range 3")
15. var range3: IntProgression = IntProgression.fromClosedRange(5,1,-1)
16. for (x in range3){
17. print("$x ")
18. }
19.
20. }

Output:

Range 1
54321
Range 2
54321
Range 3
54321

This page by mytechtalk | Kotlin Utility Functions 225


Kotlin reversed()
The reversed() function is used to return the reversed order of the given range type.

Syntax:

1. fun IntProgression.reversed(): IntProgression {


2. return IntProgression.fromClosedRange(last, first, -step)
3. }

Example of reversed() function


1. fun main(args: Array<String>) {
2. println("Reversed 1")
3. var range1 = 1..5
4. for (x in range1.reversed()){
5. print("$x ")
6. }
7. println()
8. println("Reversed 2")
9. var range2: IntRange = IntRange(1,5)
10. for (x in range2.reversed()){
11. print("$x ")
12. }
13. println()
14. println("Reversed 3")
15. var range3 = IntProgression.fromClosedRange(5,1,-1)
16. for (x in range3.reversed()){
17. print("$x ")
18. }
19. println()
20. println("Reversed 4")
21. var range4: IntProgression = IntProgression.fromClosedRange(5,1,-2)
22. for (x in range4.reversed()){
23. print("$x ")
24. }
25. }

Output:

This page by mytechtalk | Kotlin Utility Functions 226


Reversed 1
54321
Reversed 2
54321
Reversed 3
12345
Reversed 4
135

Kotlin step()
The step() function ( or step operator) is used to return the range value in interval of given step value. A step
value always takes a positive parameter. The negative step value generates the IllegalArgumentException
exception.

Example of step() function


1. fun main(args: Array<String>) {
2. val range: IntRange = 1..10
3. println("Print range value with step 2:")
4. for(x in range step (2)){
5. print("$x ")
6. }
7. println("")
8. println("Print range value with step 3:")
9. for(x in range step 3){
10. print("$x ")
11. }
12. val first=((range step 2).first)
13. val last=((range step 2).last)
14. println("")
15. println("First value of interval: $first")
16. println("Last value of interval: $last ")
17. }

Output:

Print range value with step 2:


13579
Print range value with step 3:
1 4 7 10
First value of interval: 1
Last value of interval: 9

If we provide step value as a negative integer it throws an exception.

This page by mytechtalk | Kotlin Utility Functions 227


1. fun main(args: Array<String>) {
2. val range: IntRange = IntRange(1,10)
3. for (x in range step -2){
4. print("$x ")
5. }
6. }

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Step must be positive, was: -2.


at kotlin.ranges.RangesKt__RangesKt.checkStepIsPositive(Ranges.kt:130)
at kotlin.ranges.RangesKt___RangesKt.step(_Ranges.kt:432)
at TestKt.main(Test.kt:63)

Java Interoperability
Kotlin code is fully compatible with Java code. The existing Java code can be easily called form Kotlin code and
Kotlin code is also called from Java code in normal way.

Calling Java code from Kotlin


Calling Java void method form Kotlin file
While calling a java code from Kotlin whose return types is void, it will return Unit in Kotlin file. If someone
wants to return that value, it will assign to Kotlin file by Kotlin compiler and return Unit. For example:

MyKotlinFile.kt

1. fun main(args: Array<String>) {


2. val sum= MyJavaClass.add(5, 10)
3. println("printing sum inside Kotlin file: "+sum)
4. }

MyJavaClass.java

1. public class MyJavaClass {


2. public static void main(String[] args){
3.
4. }

This page by mytechtalk | Java Interoperability 228


5. public static void add(inta,int b){
6. int result = a + b;
7. System.out.println("printing inside Java class :"+result);
8. }
9. }

Output:

printing inside Java class :15


printing sum inside Kotlin file: kotlin.Unit

Calling Java int method from Kotlin file


While calling a java code of int type or other (rather than void) from Kotlin file, it returns the result in same
types. For example, calling an area() method of Java class from Kotlin file returns result in int type.

MyKotlinFile.kt

1. fun main(args: Array<String>) {


2. val area: Int = MyJavaClass.area(3, 4)
3. println("printing area from java insideKotlin file: "+area)
4. }

MyJavaClass.java

1. public class MyJavaClass {


2. public static void main(String[] args){
3.
4. }
5. public static int area(int l, int b){
6. int result = l * b;
7. return result;
8. }
9. }

Output:

printing area from java insideKotlinfile: 12

Kotlin code calling Java class present inside package


If we want to call the Java codes from Kotlin file both present inside the different package, this requires to import
the package name with Java class inside Kotlin file.

This page by mytechtalk | Java Interoperability 229


For example, a Java class MyJavaClass.java is present inside a package myjavapackageand a Kotlin
file MyKotlinFile.kt is present inside mykotlinpackage package. In such case calling Java code from Kotlin file
needs to import myjavapackage.MyJavaClass inside Kotlin file.

MyKotlinFile.kt

1. package mykotlinpackage
2. import myjavapackage.MyJavaClass
3.
4. fun main(args: Array<String>) {
5. val area: Int = MyJavaClass.area(3, 4)
6. println("printing area from java inside Kotlin file: "+area)
7. }

MyJavaClass.java

1. package myjavapackage;
2.
3. public class MyJavaClass {
4. public static void main(String[] args){
5.
6. }
7. public static int area(int l, int b){
8. int result = l * b;
9. return result;
10. }
11. }

Output:

printing area from java inside Kotlin file: 12

Kotlin code access Java getter and setter


As Kotlin is completely interoperability with Java, we can access the getter and setter functionality of Java class
(or POJO class). For example, create a getter and setter method in Java class MyJava.java with
properties firstName and lastName. These properties are accessed from a Kotlin file MyKotlin.kt by creation
object of MyJava.java in Kotlin file.

MyJava.java

1. public class MyJava{


2. protected String firstName;
This page by mytechtalk | Java Interoperability 230
3. protected String lastName;
4.
5. public String getfirstName() {
6. return firstName;
7. }
8. public void setfirstName(String firstName) {
9. this.firstName = firstName;
10. }
11. public String getlastName() {
12. return lastName;
13. }
14. public void setlastName(String lastName) {
15. this.lastName = lastName;
16. }
17. }

MyKotlin.kt

1. fun main(args: Array<String>) {


2. val myJava = MyJava()
3.
4. myJava.lastName = "Kumar"
5. myJava.setfirstName("Arjun")
6.
7. println("accessing value using property: "+myJava.firstName)
8. println("accessing value using property: "+myJava.lastName)
9.
10. println("accessing value using method: "+myJava.getfirstName())
11. println("accessing value using method: "+myJava.getlastName())
12. }

Output:

accessing value using property: Arjun


accessing value using property: Kumar
accessing value using method: Arjun
accessing value using method: Kumar

This page by mytechtalk | Java Interoperability 231


Kotlin code access Java array
We can simply call Java class method which takes array as an argument from Kotlin file. For example, create
method sumValue() which takes array element as parameter in Java class MyJava.java calculating addition and
returns result. This method is called from Kotlin file MyKotlin.kt by passing array as parameter.

MyJava.java

1. public class MyJava {


2.
3. public intsumValues(int[] nums) {
4. int result = 0;
5. for (int x:nums) {
6. result+=x;
7. }
8. return result;
9. }
10. }

MyKotlin.kt

1. fun main(args: Array<String>){


2. val myJava = MyJava()
3. val numArray = intArrayOf(1, 2, 3,4,5)
4. val sum = myJava.sumValues(numArray)
5. println(sum)
6. }

Output:

sum of array element is 15

Kotlin code access Java Varargs


In the Java varags functionality, we can pass any number of arguments to a method. Java varargs parameter is
defined using ellipsis i.e. three dots (...) after data type.

Following points are to be kept while using the varargs parameter:

o There is only one varargs parameter in a method.

o Varargsagrument must be at the last argument.

This page by mytechtalk | Java Interoperability 232


While accessing the Java varargs from Kotlin we need to use spread operator * to pass the array.

Let's see an example in which a Java method uses an int type varargs which is called from Kotlin file.

MyJava.java

1. public class MyJava {


2. public void display(int... values) {
3. for (int s : values) {
4. System.out.println(s);
5. }
6. }
7. }

MyKotlin.kt

1. fun main(args: Array<String>){


2. val myJava = MyJava()
3. val array = intArrayOf(0, 1, 2, 3)
4. myJava.display(*array)
5. }

Output:

0
1
2
3

Let's see another example which takes two parameter in a Java method uses as parameters of String type and int
type varargs called from Kotlin file.

MyJava.java

1. public class MyJava {


2. public void display(String message,int... values) {
3. System.out.println("string is " + message);
4. for (int s : values) {
5. System.out.println(s);
6. }
7. }
8. }

MyKotlin.kt
This page by mytechtalk | Java Interoperability 233
1. fun main(args: Array<String>){
2. val myJava = MyJava()
3. val array = intArrayOf(0, 1, 2, 3)
4. myJava.display("hello",*array)
5. }

Output:

string is hello
0
1
2
3

Kotlin and Java Mapped types


Kotlin and Java types are mapped differently, however they are mapped to corresponding types. Mapping of
these types are matters only at compile time and run time remains unchanged.

Java's primitive types to corresponding Kotlin types

Java type Kotlin type

byte kotlin.Byte

short kotlin.Short

int kotlin.Int

long kotlin.Long

char kotlin.Char

double kotlin.Double

boolean kotlin.Boolean

This page by mytechtalk | Java Interoperability 234


Java's non-primitive types to corresponding Kotlin types

Java type Kotlin type

java.lang.Object kotlin.Any!

java.lang.Cloneable kotlin.Cloneable!

java.lang.Comparable kotlin.Comparable!

java.lang.Enum kotlin.Enum!

java.lang.Annotation kotlin.Annotation!

java.lang.Deprecated kotlin.Deprecated!

java.lang.CharSequence kotlin.CharSequence!

java.lang.String kotlin.String!

java.lang.Number kotlin.Number!

java.lang.Throwable kotlin.Throwable!

Java's boxed primitive types to corresponding nullableKotlin types

Java type Kotlin type

java.lang.Byte kotlin.Byte?

This page by mytechtalk | Java Interoperability 235


java.lang.Short kotlin.Short?

java.lang.Integer kotlin.Int?

java.lang.Long kotlin.Long?

java.lang.Character kotlin.Char?

java.lang.Float kotlin.Float?

java.lang.Double kotlin.Double?

java.lang.Boolean kotlin.Boolean?

Java's collection types to corresponding read-only or mutable Kotlin types

Java type Kotlin read-only type Kotlin mutable type

Iterator<T> Iterator<T> MutableIterator<T>

Iterable<T> Iterable<T> MutableIterable<T>

Collection<T> Collection<T> MutableCollection<T>

Set<T> MutableSet<T> MutableSet<T>

List<T> MutableList<T> MutableList<T>

ListIterator<T> ListIterator<T> MutableListIterator<T>

This page by mytechtalk | Java Interoperability 236


Map<K, V> Map<K, V> MutableMap<K, V>

Map.Entry<K, V> Map.Entry<K, V> MutableMap.MutableEntry<K, V>

Java Interoperability: Calling Kotlin code from


Java
As Kotlin is completely compatible with Java language. It means the application written in Java code can be
easily called from Kotlin. In the similar way ,Kotlin code is also called from Java code.

Before discussing how to call Kotlin code from Java code, let's see how Kotlin file internally looks like.

How a simple Kotlin program internally looks like.


Let's create a simple main function in a MyKotlin.kt file.

1. fun main(args: Array<String>){


2. //code
3. }
4. fun area(l: Int,b: Int):Int{
5. return l*b
6. }

After compiling the above Kotlin file MyKotlin.kt which internally looks like:

1. public class MyKotlinKt{


2. public static void main(String[] args){
3. //code
4. }
5. public static int area(int l, int b){
6. return l*b;
7. }
8. }

This page by mytechtalk | Java Interoperability: Calling Kotlin code from Java 237
The Kotlin compiler internally adds a wrapper class with naming convention MyKotlinKt. The Kotlin
file MyKotlin.kt is converted into MyKotlinKt and it is public in default. The default modifier of high level
function is public and function is converted into static as default. As the return type is Unit in MyKotlin.kt, it is
converted into void in MyKotlinKt.

Calling Kotlin code from Java code


MyKotlin.kt

1. fun main(args: Array<String>){


2. //code
3. }
4. fun area(l: Int,b: Int):Int{
5. return l*b
6. }

MyJava.java

1. public class MyJava {


2. public static void main(String[] args) {
3. int area = MyKotlinKt.area(4,5);
4. System.out.print("printing area inside Java class returning from Kotlin file: "+area);
5. }
6. }

Output:

printing area inside Java class returning from Kotlin file: 20

Java code calling Kotlin file present inside package


If we want to call the Kotlin code from Java class both present inside the different packages, this requires to
import the package name with Kotlin file name inside Java class and calling the Kotlin code from Java class.
Another way is to give full path as packageName.KotlinFileKt.methodName().

MyKotlin.kt

1. package mykotlinpackage
2.
3. fun main(args: Array<String>) {
4.
5. }
6. fun area(l: Int,b: Int):Int{
This page by mytechtalk | Java Interoperability: Calling Kotlin code from Java 238
7. return l*b
8. }

MyJava.java

1. package myjavapackage;
2. import mykotlinpackage.MyKotlinFileKt;
3.
4. public class MyJavaClass {
5. public static void main(String[] args){
6. int area = MyKotlinKt.area(4,5);
7. System.out.println("printing area inside Java class returning from Kotlin file: "+area);
8. }
9. }

Output:

printing area inside Java class returning from Kotlin file: 20

Changing the Kotlin file name using annotation


@JvmName
A Kotlin file name can be changed as wrapper class name using @JvmName annotation.

MyKotlin.kt

Write a Kotlin code and place annotation @file: JvmName("MyKotlinFileName") at the top. After compiling
Kotlin code, the file name is changed into the name provided inside annotation (in my caseMyKotlinFileName).
While accessing the code of MyKotlin.kt we require to use the file name as MyKotlinFileName.

1. @file: JvmName("MyKotlinFileName")
2. package mykotlinpackage
3.
4. fun main(args: Array<String>) {
5.
6. }
7. fun area(l: Int,b: Int):Int{
8. return l*b
9. }

MyJava.java

This page by mytechtalk | Java Interoperability: Calling Kotlin code from Java 239
1. package myjavapackage;
2. import mykotlinpackage.MyKotlinFileName;
3.
4. public class MyJavaClass {
5. public static void main(String[] args){
6. int area = MyKotlinFileName.area(4,5);
7. System.out.println("printing area inside Java class returning from Kotlin file: "+area);
8. }
9. }

Output:

printing area inside Java class returning from Kotlin file: 20

Calling method of multiple file having same generated


Java class name using@JvmMultifileClass
If the Kotlin's multiple files having same generated Java file name using @JvmName annotation, normally give
error while calling from Java file. However, Kotlin compiler generates single Java façade class which contains
generated Java file and all the declarations of the files which have same names. To active this generation façade,
we use @JvmMultifileClass annotation in all the files.

MyKotlin1.kt

1. @file: JvmName("MyKotlinFileName")
2. @file:JvmMultifileClass
3. package mykotlinpackage
4.
5. fun main(args: Array<String>) {
6.
7. }
8. fun area(l: Int,b: Int):Int{
9. return l*b
10. }

MyKotlin2.kt

1. @file: JvmName("MyKotlinFileName")
2. @file:JvmMultifileClass
3. package mykotlinpackage
4.
This page by mytechtalk | Java Interoperability: Calling Kotlin code from Java 240
5.
6. fun volume(l: Int,b: Int,h: Int):Int{
7. return l*b*h
8. }

MyJava.java

1. package myjavapackage;
2. import mykotlinpackage.MyKotlinFileName;
3.
4. public class MyJavaClass {
5. public static void main(String[] args){
6. int area = MyKotlinFileName.area(4,5);
7. System.out.println("printing area inside Java class returning from Kotlin file: "+area);
8. int vol = MyKotlinFileName.volume(4,5,6);
9. System.out.println("printing volume inside Java class returning from Kotlin file: "+vol);
10. }
11. }

Output:

printing area inside Java class returning from Kotlin file: 20


printing volume inside Java class returning from Kotlin file: 120

Kotlin property access throughconst modifier


The Kotlin properties which are annotated with const modifier in the top level as well as in class are converted
into static fields in Java. These properties are access from Java file as static properties called. For example:

MyKotlin.kt

1. constval MAX = 239


2. object Obj {
3. constval CONST = 1
4. }
5. class C {
6. companion object {
7. constval VERSION = 9
8. }
9. }

This page by mytechtalk | Java Interoperability: Calling Kotlin code from Java 241
MyJava.java

1. public class MyJava {


2. public static void main(String[] args) {
3. int c = Obj.CONST;
4. int m = MyKotlinKt.MAX;
5. int v = C.VERSION;
6. System.out.println("const "+c+"\nmax "+m+"\nversion "+v);
7. }
8. }

Output:

const 1
max 239
version 9

Kotlin Regex
Regex is generally refers to regular expression which is used to search string or replace on regex object. To use it
functionality we need to use Regex(pattern: String) class. Kotlin'sRegex class is found
in kotlin.text.regex package.

Kotlin Regex Constructor


Regex(pattern: String) It creates a regular expression from the given string pattern.

Regex(pattern: String, option: It creates a regular expression from the given string pattern and
RegexOption) given single option.

Regex(pattern: String, options: It creates a regular expression from the given string pattern and set
Set<RegexOption>) of given options.

Regex Functions
Functions Descriptions

fun containsMatchIn(input: CharSequence): It indicates that regular expression contains at least one input

This page by mytechtalk | Kotlin Regex 242


Boolean character

fun find( It returns the first match of regular expression in the input character
input: CharSequence, sequence, begins from given startIndex.
startIndex: Int = 0
): MatchResult?

fun findAll( It returns all occurrences of regular expression in the input string,
input: CharSequence, starts from the given startIndex.
startIndex: Int = 0
): Sequence<MatchResult>

funmatchEntire(input: CharSequence): It is used to match complete input character from the pattern.
MatchResult?

infix fun matches(input: CharSequence): It indicates whether all input character sequence matches in regular
Boolean expression.

fun replace(input: CharSequence, It replaces all the input character sequence of regular expression
replacement: String): String with given replacement string.

fun replaceFirst( It replaces the first occurrence of regular expression in the given
input: CharSequence, input string with given replacement string.
replacement: String
): String

fun split(input: CharSequence, limit: Int = 0): It splits the input character sequence of regular expression.
List<String>

fun toPattern(): Pattern It returns the regular expression in string.

This page by mytechtalk | Kotlin Regex 243


fun toString(): String

Example of Regex class checking contains of input pattern


1. fun main(args: Array<String>){
2. val regex = Regex(pattern = "ko")
3. val matched = regex.containsMatchIn(input = "kotlin")
4. println(matched)
5. }

Output:

true

The result of Regex function is based on matching regex pattern and the input string. Some function checks
partial match while some checks full match.

Regex example of containsMatchIn()


1. fun main(args: Array<String>){
2.
3. val regex = """a([bc]+)d?""".toRegex()
4. val matched = regex.containsMatchIn(input = "xabcdy")
5. println(matched)
6.
7. }

Output:

true

Regex example of matches(input: CharSequence): Boolean


The matches(input: CharSequence): Booleanfunction of regex checksall input character sequence matches in
regular expression.

1. fun main(args: Array<String>){


2.
3. val regex = """a([bc]+)d?""".toRegex()
4. val matched1 = regex.matches(input = "xabcdy")
5. val matched2 = regex.matches(input = "xabcdyabcd")
6. val matched3 = regex.matches(input = "abcd")

This page by mytechtalk | Kotlin Regex 244


7. println(matched1)
8. println(matched2)
9. println(matched3)
10. }

Output:

false
false
true

Regex example of matchEntire(input: CharSequence): MatchResult?


The matchEntire() function is used to match complete input character from the pattern.

1. fun main(args: Array<String>){


2.
3. val regex = Regex("abcd")
4. val matchResult1 = regex.matchEntire("abcd")?.value
5. val matchResult2 = regex.matchEntire("abcda")?.value
6.
7. val matchResult3 = Regex("""\d+""").matchEntire("100")?.value
8. val matchResult4 = Regex("""\d+""").matchEntire("100 dollars")?.value
9.
10. println(matchResult1)
11. println(matchResult2)
12. println(matchResult3)
13. println(matchResult4)
14. }

Output:

abcd
null
100
null

Regex example offind(input: CharSequence, startIndex: Int = 0):


MatchResult?
The find function is used to find the input character sequence from regex object.

1. fun main(args: Array<String>){

This page by mytechtalk | Kotlin Regex 245


2.
3. val emailParttern = Regex("""\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}""")
4. val email :String? = emailParttern.find("this is my email mymail@google.com")?.value
5. println(email)
6. val phoneNumber :String? = Regex(pattern = """\d{3}-\d{3}-\d{4}""")
7. .find("phone: 123-456-7890, e..")?.value
8. println(phoneNumber)
9. }

Output:

mymail@google.com
123-456-7890

Regex example offindAll(input: CharSequence, startIndex: Int = 0):


Sequence<MatchResult>
The findAll() function of regex returns sequence of match result on the basis of pattern provided.

1. fun main(args: Array<String>){


2. val foundResults = Regex("""\d+""").findAll("ab12cd34ef 56gh7 8i")
3. val result = StringBuilder()
4. for (findText in foundResults) {
5. result.append(findText.value + " ")
6. }
7. println(result)
8. }

Output:

12 34 56 7 8

Regex example ofreplace(input: CharSequence, replacement: String):


String
Regex replace() function replaces the all the matching pattern from input character sequence with specified
replacement string.

1. fun main(args: Array<String>){


2. val replaceWith = Regex("beautiful")
3. val resultString = replaceWith.replace("this picture is beautiful","awesome")
4. println(resultString)
This page by mytechtalk | Kotlin Regex 246
5. }

Output:

this picture is awesome

Regex example ofreplaceFirst(input: CharSequence, replacement:


String): String
Regex replaceFirst() function replaces the first occurrence of matching pattern from input character sequence
with specified replacement string.

1. fun main(args: Array<String>){


2. val replaceWith = Regex("beautiful")
3. val resultString = replaceWith.replaceFirst("nature is beautiful, beautiful is nature","awesome")
4. println(resultString)
5. }

Output:

nature is awesome, beautiful is nature

Regex example ofsplit(input: CharSequence, limit: Int = 0):


List<String>
The regex split() function splits input character sequence according to pattern provided. This splits value are
returned in List.

1. fun main(args: Array<String>){


2. val splitedValue = Regex("""\d+""").split("ab12cd34ef")
3. val nonsplited= Regex("""\d+""").split("nothing match to split" )
4. println(splitedValue)
5. println(nonsplited)
6. }

Output:

[ab, cd, ef]


[nothing match to split]

This page by mytechtalk | Kotlin Regex 247


Kotlin Regex Pattern
Regex uses several symbolic notation (patterns) in its function. Some commonly uses patterns are given below:

Symbol Description

x|y Matches either x or y

xy Matches x followed by y

[xyz] Matches either x,y,z

[x-z] Matches any character from x to z

[^x-z] '^' as first character negates the pattern. This matches anything outside the range x-z

^xyz Matches expression xyz at beginning of line

xyz$ Matches expression xyz at end of line

. Matches any single character

Regex Meta Symbols


Symbol Description

\d Matches digits ([0-9])

\D Matches non-digits

This page by mytechtalk | Kotlin Regex Pattern 248


\w Matches word characters

\W Matches non-word characters

\s Matches whitespaces [\t\r\f\n]

\S Matches non-whitespaces

\b Matches word boundary when outside of a bracket. Matches backslash when placed in a bracket

\B Matches non-word boundary

\A Matches beginning of string

\Z Matches end of String

Regex Quantifiers Patterns


Symbol Description

abcd? Matches 0 or 1 occurrence of expression abcd

abcd* Matches 0 or more occurrences of expression abcd

abcd+ Matches 1 or more occurrences of expression abcd

abcd{x} Matches exact x occurrences of expression abcd

abcd{x,} Matches x or more occurrences of expression abcd

This page by mytechtalk | Kotlin Regex Pattern 249


abcd{x,y} Matches x to y occurrences of expression abcd

Regex Sample Patterns


Pattern Description

([^\s]+(?=\.(jpg|gif|png))\.\2) Matches jpg,gif or png images.

([A-Za-z0-9-]+) Matches latter, number and hyphens.

(^[1-9]{1}$|^[1-4]{1}[0-9]{1}$|^100$) Matches any number from 1 to 100 inclusive.

(#?([A-Fa-f0-9]){3}(([A-Fa-f0- Matches valid hexa decimal color code.


9]){3})?)

((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}) Matches 8 to 15 character string with at least one upper case, one lower case and one
digit.

(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}) Matches email address.

(\<(/?[^\>]+)\>) Matches HTML tags.

This page by mytechtalk | Kotlin Regex Pattern 250

You might also like