0% found this document useful (0 votes)
15 views18 pages

Unit 1

This document provides an introduction to Kotlin, covering its concepts, installation of IntelliJ, and fundamental programming elements such as variables, conditional statements, arrays, lists, and loops. It highlights Kotlin's compatibility with Java, its features like null safety and concise syntax, and its applications in various fields including mobile and web development. Additionally, it includes code examples and explanations for using variables, conditional statements, and loops in Kotlin.

Uploaded by

ridham26kamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views18 pages

Unit 1

This document provides an introduction to Kotlin, covering its concepts, installation of IntelliJ, and fundamental programming elements such as variables, conditional statements, arrays, lists, and loops. It highlights Kotlin's compatibility with Java, its features like null safety and concise syntax, and its applications in various fields including mobile and web development. Additionally, it includes code examples and explanations for using variables, conditional statements, and loops in Kotlin.

Uploaded by

ridham26kamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit-1: Introduction to Kotlin

1.1 Concepts of Kotlin and its introduction.


1.2 Downloading IntelliJ and its settings.
1.3 Variables:
1.3.1 val vs. var,Byte,Short,Int,Long,Float,Double,Boolean, and Char.
1.3.2 String, Nullable variables.
1.4 Conditional statements: if and when. Difference between if and when.
1.4.1 ranges, types, values of function calls
1.5 Arrays and Lists:
1.5.1 create, modify, and access arrays
1.5.2 creating, modifying, and accessing lists
1.6 Loops (Iterative statements)
1.6.1 for and while loop.
1.6.2 break, continue and return

1.1 Concepts of Kotlin and its introduction.

● Kotlin is a modern, trending programming language.


● Kotlin is easy to learn,especially if you already know Java (it is 100% compatible
with Java).
● Kotlin is a programming language introduced by JetBrains in 2011.
● This is a strongly statically typed general-purpose programming language that
runs on JVM.
● In 2017, Google announced Kotlin is an official language for android
development.
● Kotlin is an open source programming language that combines object-oriented
programming and functional features into a unique platform.
● Kotlin is influenced by other popular programming languages such as Java, C#,
JavaScript, Scala and Groovy.
● The syntax of Kotlin may not be exactly similar to Java Programming Language.
➢ Following are the great companies who are using Kotlin:
● Google,Amazon,Netflix,Pinterest,Uber,Trello,Coursera,Basecamp,Corda,JetBrain
s,Many more...

Kotlin is used for:


● Mobile applications (specially Android apps)
● Web development
● Server side applications
● Data science
● And much, much more!
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

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.

fun main() Output:-


{
Kotlin: Val cannot be reassigned
val marks = 10
println("Previous marks is " +
marks)
marks = 30
println("new marks " + marks)}

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)

Byte 8 bit -128 to 127

Short 16 bit -32768 to 32767

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

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


+9,223,372,036,854,775,807

Float 32 bit 1.40129846432481707e-45 to


3.40282346638528860e+38

Double 64 bit 4.94065645841246544e-324 to


1.79769313486231570e+308

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)
}

❖ Kotlin Conditions and If..Else


Kotlin supports the usual logical conditions from mathematics:
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
● Equal to a == b
● Not Equal to: a != b
➢ Kotlin if
Use if to specify a block of code to be executed if a condition is true.
syntax
if (condition) {
// block of code to be executed if the condition is true
}
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."

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

➢ Kotlin If..Else Expressions


In Kotlin, you can also use if..else statements as expressions (assign a value to a
variable and return it)
Example:-
val time = 20
val greeting = if (time < 18) {
"Good day."
} else {
"Good evening."
}
println(greeting)}
Example
fun main() {
val time = 20
val greeting = if (time < 18) "Good day." else "Good evening."
println(greeting)
}

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)

❖ Kotlin while Loop


The while loop is used to iterate a part of program several time. Loop executed the
block of code until the condition has true. Kotlin while loop is similar to Java while loop.
Syntax
while(condition){
//body of loop
}
Example of while Loop
Let's see a simple example of while loop printing value from 1 to 5.
fun main(args: Array<String>){ Output:
var i = 1 1
while (i<=5){ 2
println(i) 3
i++ 4
} 5
}

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);
}

❖ Kotlin for Loop


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

Syntax of for loop in Kotlin:


for (item in collection){
//body of loop
}

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 "..":

Example:Print the whole alphabet:


for (chars in 'a'..'x') {
println(chars)
}

Example:You can also create ranges of number


for (nums in 5..15) {
println(nums)
}

➔ For loop Examples:-


Iterate through array: Output:
Let's see a simple example of iterating the elements of 80
array. 85
fun main() { 60
val marks = arrayOf(80,85,60,90,70) 90
for(item in marks){ 70
println(item)
}
}

Iterate through range: Output:


Let's see an example of iterating the elements of for (i in 1..5) print(i) = 12345
range. for (i in 5..1) print(i) =
fun main() { for (i in 5 downTo 1) print(i) =
54321
print("for (i in 1..5) print(i) = ") for (i in 5 downTo 2) print(i) =
for (i in 1..5) print(i) 5432
println() for (i in 1..5 step 2) print(i) = 135
print("for (i in 5..1) print(i) = ") for (i in 5 downTo 1 step 2) print(i)
for (i in 5..1) print(i) = 531
// prints nothing
println()
print("for (i in 5 downTo 1) print(i) = ")
for (i in 5 downTo 1) print(i)
println()
print("for (i in 5 downTo 2) print(i) = ")
for (i in 5 downTo 2) print(i)
println()
print("for (i in 1..5 step 2) print(i) = ")

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)
}

❖ Kotlin Break & Continue Statement

Break Statement Continue Statement

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)

val theMutableList = mutableListOf("one", "two", "three", "four")


println(theMutableList)
}

➢ Loop through Kotlin Lists


There are various ways to loop through a Kotlin list. Lets study them one by one:
Using toString() function
fun main() {
val theList = listOf("one", "two", "three", "four")
println(theList.toString())
}

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")

val itr = theList.listIterator()


while (itr.hasNext()) {
println(itr.next())
}
}
Output:
one
two
three
four

➢ Size of Kotlin List


We can use size property to get the total number of elements in a list:
fun main() {
val theList = listOf("one", "two", null, "four", "five")

println("Size of the list " + theList.size)


}

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)
}
}

The contain() Method fun main() {


The contain() method can also be val theList = listOf("one", "two", "three", "four")
used to check the existence of an
element in a list. if(theList.contains("two")){
println(true)
}else{
println(false)
}

The isEmpty() Method fun main() {


The isEmpty() method returns true if val theList = listOf("one", "two", "three", "four")
the collection is empty (contains no
elements), false otherwise. if(theList.isEmpty()){
println(true)
}else{
println(false)
}
}

The indexOf() Method fun main() {


The indexOf() method returns the val theList = listOf("one", "two", "three", "four")
index of the first occurrence of the
specified element in the list, or -1 if the println("Index of 'two' : " + theList.indexOf("two"))
specified element is not contained in }
the list.

The get() Method fun main() {


The get() method can be used to get val theList = listOf("one", "two", "three", "four")
the element at the specified index in
the list. First element index will be println("Element at 3rd position " + theList.get(2))
zero. }

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)
}

List Subtraction fun main() {


We can use - operator to subtract a list val firstList = listOf("one", "two", "three")
from another list. This operation will val secondList = listOf("one", "five", "six")
remove the common elements from val resultList = firstList - secondList
the first list and will return the result.
println(resultList)
}

Slicing a List fun main() {


We can obtain a sublist from a given val theList = listOf("one", "two", "three", "four",
list using slice() method which makes "five")
use of range of the elements indices. val resultList = theList.slice( 2..4)

println(resultList)
}

Removing null a List fun main() {


We can use filterNotNull() method to val theList = listOf("one", "two", null, "four", "five")
remove null elements from a Kotlin list. val resultList = theList.filterNotNull()

println(resultList)
}

Filtering Elements fun main() {


We can use filter() method to filter out val theList = listOf(10, 20, 30, 31, 40, 50, -1, 0)
the elements matching with the given val resultList = theList.filter{ it > 30}
predicate.
println(resultList)
}

❖ Create,Modify & Accessing Array:


➢ Kotlin Arrays
Arrays are used to store multiple values in a single variable, instead of creating
separate variables for each value.
To create an array, use the arrayOf() function, and place the values in a
comma-separated list inside it:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
Get and Set the Elements of an Array
We can access an array element by using the index number inside square brackets.
Kotlin array index starts with zero (0). So if you want to access 4th element of the array
then you will need to give 3 as the index.

16
fun main(args: Array<String>) {
val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")

println( fruits [0])


println( fruits [3])

}
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))

// Set the value at 3rd index


fruits.set(3, "Guava")
println( fruits.get(3))
}

Array Methods:

Methods() Example

Kotlin Array Length fun main(args: Array<String>) {


Kotlin provides array property called size val fruits = arrayOf<String>("Apple",
which returns the size i.e. length of the "Mango", "Banana", "Orange")
array.
println( "Size of fruits array " + fruits.size
)

Loop Through an Array fun main(args: Array<String>) {


We can use for loop to loop through an val fruits = arrayOf<String>("Apple",
array. "Mango", "Banana", "Orange")

for( item in fruits ){


println( item )
}

Check if an Element Exists fun main(args: Array<String>) {

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" )
}

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 )
}
}

18

You might also like