Unit 1-1
Unit 1-1
1
Why Use Kotlin?
● Kotlin is fully compatible with Java
● Kotlin works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
● Kotlin is concise and safe
● Kotlin is easy to learn, especially if you already know Java
● Kotlin is free to use
● Big community/support
➢ Features of Kotlin
○ Concise: Kotlin reduces writing the extra codes. This makes Kotlin more
concise.
○ Null safety: Kotlin is a null safety language( Null safety prevents errors that result
from unintentional access of variables set to null .). Kotlin aimed to eliminate the
NullPointerException (null reference) from the code Interoperable.
○ Interoperable: Kotlin easily calls the Java code in a natural way as well as Kotlin
code can be used by Java.
○ Smart cast: It explicitly typecasts the immutable values and inserts the value in
its safe cast automatically.
○ Compilation Time: It has better performance and fast compilation time.
○ Tool-friendly: Kotlin programs are build using the command line as well as any
of Java IDE.
○ Extension function: Kotlin supports extension functions and extension
properties which means it helps to extend the functionality of classes without
touching their code.
1.2 Downloading IntelliJ and its settings.
➢ Kotlin IDE
➢ The easiest way to get started with Kotlin, is to use an IDE.
➢ An IDE (Integrated Development Environment) is used to edit and compile code.
➢ we will use IntelliJ (developed by the same people that created Kotlin) which is
free to download from https://www.jetbrains.com/idea/download/.
Kotlin Install
Once IntelliJ is downloaded and installed, click on the New Project button to get
started with IntelliJ:
2
➢ Then click on "Kotlin" in the left side menu, and enter a name for your project:
➢ Then click on "Kotlin" in the left side menu, and enter a name for your project:
3
➢ Next, we need to install something called JDK (Java Development Kit) to get our
Kotlin project up and going. Click on the "Project JDK" menu, select "Download
JDK" and select a version and vendor (e.g. AdoptOpenJDK 11) and click on the
"Download" button:
➢ When the JDK is downloaded and installed, choose it from the select menu and
then click on the "Next" button and at last "Finish":
➢ Now we can start working with our Kotlin project. Do not worry about all of the
different buttons and functions in IntelliJ. For now, just open the src (source)
folder, and follow the same steps as in the image below, to create a kotlin file:
4
➢ Select the "File" option and add a name to your Kotlin file, for example "Main":
➢ You have now created your first Kotlin file (Main.kt). Let's add some Kotlin code
to it, and run the program to see how it works. Inside the Main.kt file, add the
following code:
Main.kt
fun main() {
println("Hello World")
}
5
Next, IntelliJ will build your project, and run the Kotlin file. The output will look
something like this:
1.3 Variables:
● Variables are containers for storing data values.
● To create a variable, use var or val, and assign a value to it with the equal sign
(=):
● Unlike many other programming languages, variables in Kotlin do not need to be
declared with a specified type (like "String" for text or "Int" for numbers, if you are
familiar with those).
Syntax
var variableName = value
val variableName = value
Example
var name = "John"
val birthyear = 1975
6
println(name) // Print the value of name
println(birthyear) // Print the value of birthyear
Difference between var and val
○ var (Mutable variable): We can change the value of variable declared using var
keyword later in the program.
○ val (Immutable variable): We cannot change the value of variable which is
declared using val keyword.
➢ Number Types
Number types of data are those which hold only number type data variables. It is further
categorized into different Integer and Floating point.
7
Short 16 bit -32768 to 32767
fun main() {
val myNum = 5 // Int
val myDoubleNum = 5.99 // Double
val myLetter = 'D' // Char
val myBoolean = true // Boolean
val myText = "Hello" // String
println(myNum)
println(myDoubleNum)
println(myLetter)
println(myBoolean)
println(myText)
}
8
Example:-
fun main() {
if (20 > 18) {
println("20 is greater than 18")
}
}
➢ Kotlin else
Use else to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
val time = 20
if (time < 18) {
println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
➢ Kotlin else if
Use else if to specify a new condition if the first condition is false.
Syntax:-
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
val time = 22
if (time < 10) {
println("Good morning.")
} else if (time < 20) {
println("Good day.")
9
} else {
println("Good evening.")
}
// Outputs "Good evening."
➢ Kotlin when
Instead of writing many if..else expressions, you can use the when expression, which is
much easier to read.
It is used to select one of many code blocks to be executed:
Example
Use the weekday number to calculate the weekday name:
val day = 4
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
10
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
// Outputs "Thursday" (day 4)
Example:
fun main(){ Output:
var i = 1 1
do { 2
println(i) 3
11
i++ 4
} 5
while (i<=5);
}
Example:-
fun main() {
val marks = arrayOf(80,85,60,90,70)
for(item in marks){
println(item)
}
}
❖ Kotlin Ranges
With the for loop, you can also create ranges of values with "..":
12
fun main() { 60
val marks = arrayOf(80,85,60,90,70) 90
for(item in marks){ 70
println(item)
}
}
The break statement is used to terminate Kotlin, continue statement is used to repeat
the loop immediately without evaluating the the loop. It continues the current flow of the
loop condition. program and skips the remaining code at
Syntax:- specified condition.
13
for(..){
//body of for Syntax:-
if(checkCondition){ for(..){
break; //body of for above if
} if(checkCondition){
} continue
}
//body of for below if
}
Example: Example:
fun main() { fun main() {
for (i in 1..5) { for (i in 1..3) {
if (i == 3) { println("i = $i")
break if (j == 2) {
} continue
println(i) }
} println("this is below if")
} }
}
Output: Output:
1 i=1
2 this is below if
3 i=2
i=3
❖ Kotlin - Lists
Kotlin list is an ordered collection of items. A Kotlin list can be either mutable
(mutableListOf) or read-only (listOf). The elements of list can be accessed using
indices. Kotlin mutable or immutable lists can have duplicate elements.
Creating Kotlin Lists
For list creation, use the standard library functions listOf() for read-only lists and
mutableListOf() for mutable lists.
Example:
fun main() {
val list = listOf("one", "two", "three", "four")
println(list)
14
}
When you run the above Kotlin program, it will generate the following output:
[one, two, three, four]
➢ Using Iterator
fun main() {
val theList = listOf("one", "two", "three", "four")
Output:
Size of the list 5
15
➢ Methods() in List:
Methods() Example:
in operator
The "in" Operator fun main() {
val theList = listOf("one", "two", "three", "four")
can be used to check the
existence of an element in if("two" in theList){
a list. println(true)
}else{
println(false)
}
}
16
}
println(resultList)
}
println(resultList)
}
Example:-
fun main(args: Array<String>){
17
for(element in stringList){
print(element+" ")
}
println()
println(stringList.get(0))
println(stringList.indexOf("Vijay"))
println(stringList.lastIndexOf("Vijay"))
println(stringList.size)
println(stringList.contains("Prakash"))
println(stringList.containsAll(list))
println(stringList.subList(2,4))
println(stringList.isEmpty())
println(stringList.drop(1))
println(stringList.dropLast(2))
}
Output:
Ajay Vijay Prakash Vijay Rohan
Ajay
1
3
5
true
true
[Prakash, Vijay]
false
[Vijay, Prakash, Vijay, Rohan]
[Ajay, Vijay, Prakash]
➢ mutableListOf() Methods
Function Descriptions
18
abstract fun It adds a0ll the elements of given collection to current
addAll(elements: collection.
Collection<E>): Boolean
abstract fun listIterator(): It returns a list iterator over the elements in proper
MutableListIterator<E> sequence in current list.
abstract fun listIterator9 It returns a list iterator starting from specified index over
(index: Int): the elements in list in proper sequence.
MutableListIterator<E>
abstract fun It removes all the elements from the current list which are
removeAll(elements: also present in the specified collection.
Collection<E>): Boolean
abstract fun It retains all the elements within the current collection
retainAll(elements: which are present in given collection.
Collection<E>): Boolean
abstract operator fun It replaces the element and add new at given index with
set(index: Int, element: specified element.
E): E
abstract fun subList( It returns part of list from specified fromIndex (inclusive)
fromIndex: Int, to toIndex (exclusive) from current list. The returned list is
toIndex: Int backed by current list, so non-structural changes in the
): MutableList<E> returned list are reflected in current list, and vice-versa.
19
fun main() {
val theList = mutableListOf("Priya","riya")
theList.add("siya")
theList.add(1,"Miya")
val l = mutableListOf("niya","jiya")
theList.addAll(l)
// theList.remove("riya")
// theList.removeAt(3)
println(theList)
println( fruits.get(0))
println( fruits.get(3))
20
fruits.get(3)
}
Array Methods:
Methods() Example
for(item in fruits){
println(item)
}
21
Distinct Values from Array fun main(args: Array<String>) {
Kotlin allows to store duplicate values in val fruits = arrayOf<String>("Apple",
an array, but same time you can get a set "Mango", "Banana", "Orange", "Apple")
of distinct values stored in the array using
distinct() member function. val distinct = fruits.distinct()
for( item in distinct ){
println( item )
}
}
22