Kotlin First Program Concept
Kotlin First Program Concept
Let's understand the concepts and keywords of Kotlin program 'Hello World.kt'.
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.
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.
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.
It is not necessary to initialize variable at the time of its declaration. Variable can be initialized later on when the
program is executed.
Example
In Kotlin, everything is an object, which means we can call member function and properties on any variable.
o Number
o Character
o Boolean
o Array
o String
Example
Example
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.
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]
String declaration:
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.
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.
In Java
int value1 = 10;
long value2 = value1; //Valid code
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()
We can also converse from larger data type to smaller data type.
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.
Output:
15
5
50
2
0
Relation Operator
Relation operator shows the relation and compares between operands. Following are the different relational
operators:
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.
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.
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.
&& 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)
Output:
Bitwise Operation
In Kotlin, there is not any special bitwise operator. Bitwise operation is done using named function.
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 Output
Kotlin output operation is performed using the standard methods print() and println(). Let's see an example:
Output
Hello World!
Welcome to JavaTpoint
The methods print() and println() are internally call System.out.print() and System.out.println() respectively.
o println(): println() method is used to print values provided inside the method "()" and moves cursor to the
beginning of next line.
Example
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:
Output:
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.
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:
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.
Output
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 nested if expression
Traditional if Statement
Syntax of traditional if statement
if(condation){
//code statement
}
Output:
We can remove the curly braces of if-else body by writing if expression in only one statement.
For example:
Using if-else expression in one single line statement is like ternary operator in Java. Kotlin does not support
any ternary operator.
Output:
10 is positive
Output:
body of if 30
Output:
For Example
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
For Example
Output:
Monday
First day of the week
Output:
It is rainy season
For Example:
Output:
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 {}.
The elements of an array are iterated on the basis of indices (index) of array. For example:
Output:
marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70
Output:
Syntax
while(condition){
Output:
1
2
3
4
5
For example:
Output:
infinite loop
infinite loop
infinite loop
.
.
.
.
infinite loop
infinite loop
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);
Output:
1
2
3
4
5
Output:
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.
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 is used to terminate the specific loop. This is done by using break expression
with @ sign followed by label name (break@loop).
Output:
i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 2 and j = 1
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.
Output:
i=1
this is below if
i=2
i=3
this is below if
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).
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.
For example
Output:
o Here, sqrt() is a library function which returns square root of a number (Double 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()
Output:
sum = 11
code after sum
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.
Output:
11
Syntax
1. fun functionName(){
2. .. .. ..
3. functionName() //calling same function
4. }
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
Output:
Factorial of 5 = 120
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
General Recursion
Let's see an example of calculating sum of nth (100000 larger number) using general (normal) recursion.
Output:
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.
Output:
Output:
Factorial of 4 = 24
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.
Output:
In the above program, run() function calls with no argument, the default parameter are used in function
definition.
Output:
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.
Output:
As all the arguments are passed in run() function call, the parameters of function definition uses the argument
passed in function call.
For example:
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.
Output:
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.
Output:
15
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.
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:
Output:
The above higher order function can also be called in another ways as below mention code in main() function:
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 Function expressions
Output:
Output:
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.
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.
Output:
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.
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.
Output:
11
12
Output:
13
14
For example:
Output:
10
15
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
Output:
at ArrayListKt.main(Array.kt:4)
Output:
10
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.
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.
indices: IntRange It returns the ranges of valid character indices from current 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.
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.
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.
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.
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 is also used in arbitrary expression in curly braces to evaluate a string expression. This is done by
using dollar sign $.
Output:
value 10
is greater than value 5
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.
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.
While using raw string with new line, it generates a | as margin prefix. For example:
Output:
Output:
Output:
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.
Output:
true
false
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.
Output:
false
true
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.
There are four different keywords used in exception handling. These are:
o try
o catch
o finally
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.
o ArrayIndexOutOfBoundExceptions: thrown when an array has been tried to access with incorrect index value.
o IOException.
o SQLException etc.
1. try{
2. //code that may throw exception
3. }finally{
4. // code finally block
5. }
This above program generates an exception, which causes rest of code below the exception not executable.
Output:
Output:
java.lang.ArithmeticException: / by zero
code below exception...
In the above program after implementing try - catch block, rest of code below exception executes.
Output:
10
Output:
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.
Let's modify above code and place catch block from general exception to specific exception.
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.
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
Output:
2
finally block always executes
below codes...
Output:
Output:
java.lang.ArithmeticException: / by zero
finally block always executes
below codes...
Let's see an example of throw keyword in which we are validating age limit for driving license.
Output:
Kotlin's type system is aimed to eliminate NullPointerException form the code. NullPointerException can only
possible on following causes:
o An uninitialized of this operator which is available in a constructor passed and used somewhere.
Nullable Types
Nullable types are declared by putting a ? behind the String as:
Output:
null
Output:
Error:(3, 11) Kotlin: Null can not be a value of a non-null type String
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.
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.
Output:
String length is 64
Output:
String length is 64
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.
A nullable string (String?) cannot be cast to non nullabe string (String), this 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.
Output:
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.
Output:
Kotlin
null
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.
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.
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:
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.
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:
Output:
str = abc
strLength = 3
strLength2 = 3
check(null,"mango") = null
check("apple","orange") =
textOne = apple
textTwo = orange
Let's see an example of array in Kotlin. In this example we will see how to initialize and traverse its elements.
Output:
0
0
0
0
0
Output:
0
10
0
15
0
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
Output:
Output:
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.
2. Mutable Collection
Immutable Collection:
Immutable collection also called Collection supports read only functionalities. Methods of immutable collection
that supports read functionalities are:
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:
List ArrayList<T>()
arrayListOf()
mutableListOf()
Map HashMap
hashMapOf()
mutableMapOf()
Set hashSetOf()
mutableSetOf()
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.
Functions Descriptions
abstract fun contains(element: E): It checks specified element is contained in this collection.
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).
Output:
Ajay
Vijay
Prakash
Output:
1
2
3
Ajay
Vijay
Prakash
1
2
3
Ajay
Vijay
Prakash
Output:
Output:
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.
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.
Function Descriptions
abstract fun add(element: E): It adds the given element to the collection.
Boolean
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.
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.
Output:
Ajay
Vijay
Prakash
Vijay
Ajay
This page by mytechtalk | Kotlin MutableList (mutableListOf()) 85
Vijay
Prakash
Vijay
Output:
Ajay
Vijay
Prakash
Vijay
Ajeet
Amit
Akash
mutableList.add("Ajay") // index 0
mutableList.add("Vijay") // index 1
mutableList.add("Prakash") // index 2
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)....")
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
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.
ArrayList(elements: Collection<E>) It is used to create an ArrayList filled from the elements of collection.
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 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.
Output:
......print ArrayList......
Ajay
Vijay
Prakash
Rohan
Vijay
Output:
.......print ArrayList1......
Ajay
Vijay
Prakash
Rohan
Vijay
size of arrayList1 = 5
......print ArrayList2......
14
20
80
size of arrayList2 = 3
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
size of arrayList = 3
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.get(2).......
Prakash
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.set(2,"Ashu").......
.......print ArrayList.......
Ajay
Vijay
Ashu
Rohan
Vijay
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.indexOf("Vijay").......
1
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.lastIndexOf("Vijay").......
4
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.remove("Vijay").......
Ajay
Prakash
Rohan
Vijay
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.remove(3).......
Ajay
Vijay
Prakash
Vijay
Output:
This page by mytechtalk | Kotlin ArrayList class 100
.......print ArrayList.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......arrayList.clear().......
.......arrayList.......
[]
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.
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.
Output:
4
7
12
Output:
Output:
.......print ArrayList.......
Ajay
Vijay
Prakash
Output:
.......print list.......
Ajay
Vijay
Prakash
Rohan
Vijay
.......list.get(2).......
Prakash
Output:
.......print list.......
Ajay
Vijay
Prakash
.......list.set(2,"Rohan").......
.......print list.......
Ajay
Vijay
Rohan
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:
To use the Map interface we need to use its function called mapOf() or mapOf<k,v>().
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 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(
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>>
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>
Output:
Ajay
Vijay
Prakash
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
The implementation of HashMap class does not make guarantees about the order of data of key, value and entries
of collections.
HashMap(original: Map<out K, V>) It constructs a HashMap instance filled with contents of specified
original map.
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.
open fun containsValue(value: V): It returns true if map maps one of more keys to specified value.
Boolean
open fun remove(key: K): V? It removes the specified key and its corresponding value from map
Output:
.....traversing hashmap.......
Element at key 1 = Ajay
Element at key 2 = Ajay
Element at key 3 = Vijay
Element at key 4 = Praveen
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
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
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.
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
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().......
{}
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
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 remove(key: K): V? It removes the specified key and its corresponding value from map
Output:
.....traverse intMap........
Ashu
Ajeet
Vijay
Rohan
......traverse stringMap.......
Ashu
Development
Delhi
Playing
......traverse anyMap.......
Rohsan
Ashu
200
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
Output:
......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
.......stringMap.containsValue("Delhi")......
true
false
Output:
......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.contains("city").......
true
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
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
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]
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
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
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.
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
Output:
......traverse stringMap.......
Key = city , value = Delhi
Key = name , value = Ashu
Key = department , value = Development
Key = hobby , value = Playing
......stringMap.clear().......
kotlin.Unit
{}
To use the MutableMap interface we need to use its function called mutableMapOf() or mutableMapOf
<k,v>().
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.
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.
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
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
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
Output:
......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......mutableMap.containsKey("city").......
true
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
Output:
......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......mutableMap.contains("city").......
true
Output:
......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.......mutableMap.get("department")......
Development
Output:
......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.......mutableMap.getValue("department")......
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
Output:
......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
.....mutableMap.count()........
4
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
Output:
......traverse mutableMap.......
Key = name, Value = Ashu
Key = city, Value = Delhi
Key = department, Value = Development
Key = hobby, Value = Playing
......mutableMap.clear().......
kotlin.Unit
{}
Set interface uses setOf() function to create the list of object of set interface which contains list of elements.
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
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(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.
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> 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?
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
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.
Output:
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.
Output:
Output:
Output:
Set interface uses mutableSetOf() function to create the list of object of set interface which contains list of
elements.
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.
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>.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.
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
Output:
....intmutableSet....
2
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.
Output:
....intmutableSet....
2
6
4
29
5
Output:
....intmutableSet....
2
6
4
29
5
Output:
....mutableSet1....
2
6
4
29
5
....mutableSet2....
[6, 8, 11, 22]
....mutableSet3....
[2, 4, 6]
....mutableSet1.contains(29)....
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
Output:
....mutableSet1....
2
6
4
29
5
....mutableSet1.first()....
2
...mutableSet1.indexOf(4)...
2
...mutableSet1.drop(3)...
[29, 5]
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.
Output:
......traversing hashSet......
8
2
13
5
6
Output:
......traversing hashSetOf1......
8
2
13
5
6
......traversing hashSetOf2......
Ashu
Roshan
Vijay
......traversing hashSet......
8
2
13
5
6
......traversing hashSet after hashSet.addAll(intSet)......
2
4
5
6
8
13
29
Output:
......traversing hashSetOf1......
2
4
13
29
6
15
.....hashSetOf1.size.....
Output:
......traversing hashSetOf1......
2
4
13
29
6
15
.....hashSetOf1.remove(6)......
true
......traversing hashSetOf1 after remove(6)......
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.
@MustBeDocumented This meta-document specifies that the annotation is the part of the public API and should
be included in the class or method.
Declaring an annotation
Annotation is declared by placing annotation modifier in front of a class.
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.
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:
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
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. }
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:
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).
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:
Output:
[5,10]
In the above program ::isPositive is a value of function type (Int) -> Boolean.
Create a function isPositive() which takes two different types Int and String and call this function with different
type parameter.
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.
Output:
5
x
10
Output:
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.
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:
Create an object
Kotlin object is created in two steps, the first is to create reference and then create an object.
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() {
Output:
1. class outerClass{
2. //outer class code
3. class nestedClass{
4. //nested class code
5. }
6. }
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:
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.
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:
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.
1. Primary constructor
2. Secondary constructor
There is only one primary constructor in a Kotlin class whereas secondary constructor may be one or more.
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.
When the object of myClasss is created, it initializes name and id with "Ashu" and "101" respectively.
Output:
Name = Ashu
Id = 101
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.
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.
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:
Output:
Name = Ashu
Id = 101
Password = mypassword
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:
Output:
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.
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.
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.
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.
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.
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).
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)
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.
All Kotlin classes have a common superclass "Any". It is a default superclass for a class with no supertypes
explicitly specified.
1. class Example
For example:
For example:
Output:
x is equal to 10
Output:
flying...
swimming...
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.
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:
}
}
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.
For example,
Output:
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.
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.
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.
}
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.
Output:
Parrot is flying...
Duck is flying...
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.
For example:
Output:
Bird is flying...
Parrot is flying...
Green
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.
Output:
Bird is flying...
Duck is flying...
Parrot is flying...
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.
Output:
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.
Output:
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.
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.
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:
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>) {
Output:
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:
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")
}
}
super<MyInterface2>.absMethod()
}
}
Output:
Declaring a data class must contains at least one primary constructor with property argument (val or var).
o equals(): Boolean
o hashCode(): Int
o toString(): String
o copy()
Due to presence of above functions internally in data class, the data class eliminates the 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) {
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,"[email protected]");
4. System.out.println(u);
5. }
6. }
Output:
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
Output:
o Before 1.1,data class may only implements interface. After that data classes may extend other classes.
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.
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 .
Output:
Product(name=laptop, price=25000)
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.
Output:
true
true
Output:
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)
Sealed class is used when the object have one of the types from limited set, but cannot have any other type.
The subclasses of sealed classes must be declared in the same file in which sealed class itself.
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. }
For example:
Output:
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.
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:
The above example only demonstrates about how to declare an extension 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.
Output:
Let's rewrite the above program using extension function as nullable receiver.
Output:
A class which contains companion object can also be defined as extension function and property for the
companion object.
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:
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:
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 Compile time checking: Generics code is checked at compile time so that it can avoid any problems at runtime.
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.
Output:
30
40
1. class_or_interface<Type>
1. <Type>methodName(parameter: classType<Type>)
Output:
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.
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.
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.
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.
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. }
Output:
12345
54321
12345
54321
Output:
a bcde
edcba
Output:
13579
10 7 4 1
Output:
abcde
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.
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.
Output:
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:
Output:
Range 1
54321
Range 2
54321
Range 3
54321
Syntax:
Output:
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.
Output:
Output:
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.
MyKotlinFile.kt
MyJavaClass.java
Output:
MyKotlinFile.kt
MyJavaClass.java
Output:
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:
MyJava.java
MyKotlin.kt
Output:
MyJava.java
MyKotlin.kt
Output:
Let's see an example in which a Java method uses an int type varargs which is called from Kotlin file.
MyJava.java
MyKotlin.kt
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
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
byte kotlin.Byte
short kotlin.Short
int kotlin.Int
long kotlin.Long
char kotlin.Char
double kotlin.Double
boolean kotlin.Boolean
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.lang.Byte kotlin.Byte?
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?
Before discussing how to call Kotlin code from Java code, let's see how Kotlin file internally looks like.
After compiling the above Kotlin file MyKotlin.kt which internally looks like:
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.
MyJava.java
Output:
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:
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:
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:
MyKotlin.kt
This page by mytechtalk | Java Interoperability: Calling Kotlin code from Java 241
MyJava.java
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.
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
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>
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.
Output:
true
Output:
false
false
true
Output:
abcd
null
100
null
Output:
[email protected]
123-456-7890
Output:
12 34 56 7 8
Output:
Output:
Output:
Symbol Description
xy Matches x followed by y
[^x-z] '^' as first character negates the pattern. This matches anything outside the range x-z
\D Matches non-digits
\S Matches non-whitespaces
\b Matches word boundary when outside of a bracket. Matches backslash when placed in a bracket
((?=.*\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.