Unit 1
Unit 1
1
● 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:
➢ 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:
3
➢ 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:
➢ Select the "File" option and add a name to your Kotlin file, for example "Main":
4
➢ 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")
}
Next, IntelliJ will build your project, and run the Kotlin file. The output will look
something like this:
5
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
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.
6
➢ Kotlin Data Type
Data type (basic type) refers to type and size of data associated with variables and
functions. Data type is used for declaration of memory location of variable which
determines the features of data.
In Kotlin, everything is an object, which means we can call member function and
properties on any variable.
Kotlin built in data type are categorized as following different categories:
○ Number
○ Character
○ Boolean
○ Array
○ String
➢ Number Types
Number types of data are those which hold only number type data variables. It is further
categorized into different Integer and Floating point.
Data Bit Width Data Range
Type (Size)
fun main() {
val myNum = 5 // Int
val myDoubleNum = 5.99 // Double
val myLetter = 'D' // Char
val myBoolean = true // Boolean
val myText = "Hello" // String
7
println(myNum)
println(myDoubleNum)
println(myLetter)
println(myBoolean)
println(myText)
}
8
➢ 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.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
9
➢ 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"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
// Outputs "Thursday" (day 4)
10
Kotlin do-while Loop
The do-while loop is similar to while loop except one key difference. A do-while loop first execute
the body of do block after that it check the condition of while.
Syntax
do{
//body of do block
}
while(condition);
Example:
fun main(){ Output:
var i = 1 1
do { 2
println(i) 3
i++ 4
} 5
while (i<=5);
}
Example:-
fun main() {
val marks = arrayOf(80,85,60,90,70)
for(item in marks){
println(item)
}
}
11
❖ Kotlin Ranges
With the for loop, you can also create ranges of values with "..":
12
for (i in 1..5 step 2) print(i)
println()
print("for (i in 5 downTo 1 step 2) print(i) = ")
for (i in 5 downTo 1 step 2) print(i)
}
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.
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
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.
13
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 theList = listOf("one", "two", "three", "four")
println(theList)
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")
14
Output:
Size of the list 5
➢ Methods() in List:
Methods() Example:
The "in" Operator fun main() {
The in operator can be used to check val theList = listOf("one", "two", "three", "four")
the existence of an element in a list.
if("two" in theList){
println(true)
}else{
println(false)
}
}
15
List Addition fun main() {
We can use + operaator to add two or val firstList = listOf("one", "two", "three")
more lists into a single list. This will val secondList = listOf("four", "five", "six")
add second list into first list, even val resultList = firstList + secondList
duplicate elements will also be added.
println(resultList)
}
println(resultList)
}
println(resultList)
}
16
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
}
Kotlin also provides get() and set() member functions to get and set the value at a
particular index. Check the following example:
Example
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")
println( fruits.get(0))
println( fruits.get(3))
Array Methods:
Methods() Example
17
val fruits = arrayOf<String>("Apple",
We can use the in operator alongwith "Mango", "Banana", "Orange")
if...else to check if an element exists in an
array. if ("Mango" in fruits){
println( "Mango exists in fruits" )
}else{
println( "Mango does not exist in
fruits" )
}
18