SlideShare a Scribd company logo
1 of 50
Compose
Code
Camp
GDSC ANDROID
DEVELOPMENT TEAM,
GPREC.
Topics :-
 Introduction
 KeyWords
 Input Output
 Data Types
 Operators
 Flow Controls
 Functions
INTRODUCTION TO KOTLIN
Kotlin is a programming language introduced by JetBrains in 2011, the official designer of the most
intelligent java ide, named Intellij Idea. Kotlin is free, has been free and will remain free. It is
developed under the apache 2.0 license. This is a strongly statically typed general-purpose
programming language that runs on jvm. Following are the great companies who are using Kotlin:
•Google
•Amazon
•Netflix
•Pinterest
•Many more…..
Kotlin Program Entry Point :-
 Anentrypoint of a Kotlinapplication is themain()function.
fun main()
{
var string: String = "Hello, World!"
println("$string")
}
(or)
fun main(args: Array<String>)
{
println("Hello, world!")
}
Kotlin - Keywords
Kotlinkeywordshavebeencategorizedintothreebroadcategories:(a)HardKeywords(b) SoftKeywords(c) ModifierKeywords
Kotlin Hard Keywords
as as? break class
continue do else false
for fun if in
!in interface is !is
null object package return
super this throw true
try typealias typeof val
var when while
Kotlin - Keywords
Kotlin Soft Keywords
by catch constructor delegate
dynamic field file finally
get import init param
property receiver set setparam
value where
Kotlin Modifier Keywords
actual abstract annotation companion
const crossinline data enum
expect external final infix
inline inner internal lateinit
noinline open operator out
override private protected public
reified sealed suspend tailrec
vararg
Kotlin - Variables
Variables are an important part of any programming. They are the names you givetocomputer memory locations which are usedto store values in a computer program and later you use those names to
retrievethestoredvaluesandusetheminyourprogram.Kotlinvariablesarecreatedusingeithervar orval keywordsand thenanequalsign= isusedtoassignavaluetothosecreatedvariables.
Kotlin Mutable Variables
Mutablemeansthatthevariablecan bereassignedtoadifferentvalueafterinitialassignment.To declareamutablevariable,weusethevarkeyword
fun main()
{
var name = "Zara Ali"
println("Name = $name")
name = "Nuha Ali"
println("Name = $name")
}
Kotlin - Variables
Kotlin Read-only Variables
Aread-only variable can be declared using val (instead ofvar)andonce a valueis assigned, it can not bere-assigned.
Kotlin Variable Naming Rules
Therearecertainrulestobe followedwhile namingthe Kotlinvariables:
•Kotlinvariablenamescancontainletters,digits,underscores,anddollarsigns.
•Kotlinvariablenamesshouldstartwitha letter,$ orunderscores
•KotlinvariablesarecasesensitivewhichmeansZaraandZARA aretwo differentvariables.
•Kotlinvariablecannothaveany whitespaceorothercontrolcharacters.
•Kotlinvariablecannothavenameslike var,val,String,Intbecausethey arereservedkeywordsinKotlin.
Kotlin - Data Types
Kotlin built indatatype canbe categorizedasfollows:
 Number
 Character
 String
 Boolean
 Array
(a) Kotlin Number Data Types :-
Data Type Size (bits) Data Range
Byte 8 bit -128 to 127
Short 16 bit -32768 to 32767
Int 32 bit -2,147,483,648 to 2,147,483,647
Long 64 bit -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
Float 32 bit 1.40129846432481707e-45 to
3.40282346638528860e+38
Double 64 bit 4.94065645841246544e-324 to
1.79769313486231570e+308
Example :-
fun main(args: Array<String>)
{
val a: Int = 10000
val d: Double = 100.00 val
f: Float = 100.00f
val l: Long = 1000000004
val s: Short = 10
val b: Byte = 1
println("Int Value is " + a)
println("Double Value is " + d)
println("Float Value is " + f)
println("Long Value is " + l )
println("Short Value is " + s)
println("Byte Value is " + b) }
(b) Kotlin Character Data Type :-
fun main(args: Array<String>)
{
val letter: Char // defining a Char variable
letter = 'A' // Assigning a value to it
println("$letter")
}
Kotlin String Data Type :-
The Stringdata type is used tostore a sequence ofcharacters. String values must be surrounded by double quotes ("") ortriplequote (""" """).
We have twokinds ofstring available in Kotlin- one iscalled EscapedString andanother iscalled Raw String.
•Escapedstring isdeclared within double quote (" ")andmay contain escape characters like 'n', 't','b' etc.
•Raw string is declared within triplequote (""" """) andmay contain multiple lines oftext without any escape characters.
Example:-
fun main(args: Array<String>)
{
val escapedString : String = "I am escaped String!n"
var rawString :String = """This is going to be a multi-line string and will not have any escape
sequence""";
print(escapedString)
println(rawString)
}
Kotlin Boolean Data Type :-
Boolean is very simple like other programminglanguages. We have only twovalues forBoolean data type - either true orfalse.
fun main(args: Array<String>)
{
val A: Boolean = true // defining a variable with true value
val B: Boolean = false // defining a variable with false value
println("Value of variable A "+ A )
println("Value of variable B "+ B )
}
Kotlin Array Data Type :-
Kotlin arraysareacollection ofhomogeneous data.Arrays areused tostore multiple values in a single variable,instead of declaring separate variablesforeach
value.
fun main(args: Array<String>)
{
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Value at 3rd position : " + numbers[2])
}
Kotlin Data Type Conversion :-
Typeconversionisa processinwhichthevalue ofone datatype isconvertedintoanothertype. Kotlindoesnotsupportdirectconversionofonenumericdatatype toanother,
For example,itisnotpossibletoconvertanInttype to aLongtype:
To convert a numeric data type to another type, Kotlin provides a set of functions:
 toByte()
 toShort()
 toInt()
 toLong()
 toFloat()
 toDouble()
 toChar()
Kotlin Operators
Operators are the special symbols that perform different operation on operands. For example
+ and – are operators that perform addition and subtraction respectively. Like Java, Kotlin
contains different kinds of operators.
• Arithmetic operator
• Relation operator
• Assignment operator
• Unary operator
• Logical operator
• Bitwise operator
Arithmetic Operators
Operators Meaning Expression Translate to
+ Addition a + b a.plus(b)
– Subtraction a – b a.minus(b)
* Multiplication a * b a.times(b)
/ Division a / b a.div(b)
% Modulus a % b a.rem(b)
Relation Operators
Operators Meaning Expression Translate to
> greater than a > b a.compareTo(b) > 0
< less than a < b a.compareTo(b) < 0
>= greater than or equal to a >= b a.compareTo(b) >= 0
<= less than or equal to a <= b a.compareTo(b) <= 0
== is equal to a == b a?.equals(b) ?: (b === null)
!= not equal to a != b !(a?.equals(b) ?: (b === null)) > 0
Assignment Operators
Operators Expression Translate to
+= a = a + b a.plusAssign(b) > 0
-= a = a – b a.minusAssign(b) < 0
*= a = a * b a.timesAssign(b)>= 0
/= a = a / b a.divAssign(b) <= 0
%= a = a % b a.remAssign(b)
Unary Operators
Operators Expression Translate to
++ ++a or a++ a.inc()
— –a or a– a.dec()
Logical Operators
Operators Meaning Expression
&& return true if all expressions are true (a>b) && (a>c)
|| return true if any of expression is true (a>b) || (a>c)
! return complement of the expression a.not()
Bitwise Operators
Operators Meaning Expression
shl signed shift left a.shl(b)
shr signed shift right a.shr(b)
ushr unsigned shift right a.ushr()
and bitwise and a.and(b)
or bitwise or a.or()
xor bitwise xor a.xor()
inv bitwise inverse a.inv()
Kotlin Control Flow Statements :-
Kotlin flow control statements determine the next statement tobe executed. For example,
 if
 if – else
 when
 while
 for
 do
Kotlin if...else Expression
Kotlin if...else canalso be used asanexpression whichreturnsa valueand thisvaluecanbe assigned to avariable.Below is a simple
syntaxof Kotlinif...else expression:
val result = if (condition) {
// code block A to be executed if condition is true
} else {
// code block B to be executed if condition is false
}
Example
fun main(args: Array<String>) {
val age:Int = 10
val result = if (age > 18) {
"Adult"
} else {
"Minor"
}
println(result)
}
Kotlin when expression
when expression is far easy and more clean in comparison to writing many if...else if expressions. Kotlin when expression evaluates a
sectionof code among manyalternativesasexplained in below example.
Kotlin when matchesits argumentagainstall branchessequentiallyuntilsome branchcondition is satisfied.
Kotlin when expression is similar to the switch statementin C, C++ and Java.
Example 1
fun main(args: Array<String>) {
val day = 2
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
}
Example 2
We cancombine multiple when conditions into asingle condition.
fun main(args: Array<String>) {
val day = 2 when (day) {
1, 2, 3, 4, 5 -> println("Weekday")
else -> println("Weekend")
}
}
Example 3
Kotlin rangesarecreatedusing double dots .. andwe canusethem while checking when condition withthehelpof inoperator.
fun main(args: Array<String>) {
val day = 2
when (day) {
in 1..5 -> println("Weekday")
else -> println("Weekend")
}
}
Kotlin For loop
Kotlin forloop iteratesthroughanythingthatprovides aniterator ie. thatcontainsa countablenumber of values,for example arrays,
ranges,maps or anyother collection availablein Kotlin.
Kotlin does notprovide a conventionalforloop whichis available inC, C++ andJavaetc. Syntax
Thesyntaxof theKotlin forloop is asfollows:
for (item in collection) {
// body of loop
}
Example 1
Following is anexample wheretheloop iteratesthroughthe rangeandprintsindividual item. To iterateover a rangeof numbers, we
willuse arangeexpression:
fun main(args: Array<String>) {
for (item in 1..5) {
println(item)
}
}
Example 2
Let's seeone more example wheretheloop williteratethroughanotherrange,but thistime it willstep down insteadof stepping up asin
theabove example:
fun main(args: Array<String>) {
for (item in 5 downTo 1 step 2) {
println(item)
}
}
Example 3
Following is anexample wherewe used forloop to iteratethroughanarrayof strings:
fun main(args: Array<String>) {
var fruits = arrayOf("Orange", "Apple", "Mango", "Banana")
for (item in fruits) {
println(item)
}
}
Kotlin – while loop
Kotlin whileloop executes itsbody continuouslyaslong asthespecified condition is true.
Kotlin whileloop is similar to Java while loop.
Syntax :
Thesyntaxof theKotlin whileloop is asfollows:
while (condition) {
// body of the loop
}
Example
Following is anexample wherethewhile loop continueexecuting thebody of theloop aslong asthecountervariable i is greaterthan0:
fun main(args: Array<String>) {
var i = 5;
while (i > 0) {
println(i) i–
}
}
Kotlin – do … while loop
Thedo..while is similar to the while loop with a difference that the this loop will execute the code block once,before checkingif the condition
is true,then it will repeat the loop as long as the condition is true.
Theloop will always be executed at least once, even if the condition is false, because the code block is executedbefore the condition is tested.
Syntax:
Thesyntax of theKotlin do...while loop is as follows:
do{
// body of the loop
}while( condition )
Example
Following is anexample wherethedo...while loop continueexecutingthe body of the loop as long asthecountervariable i is greater
than0:
fun main(args: Array<String>) {
var i = 5;
do{
println(i)
i–
}while(i > 0)
}
Kotlin – Break Statement
Kotlin breakstatement is usedto come out of a loop once a certain condition is met. This loop could bea for, while ordo...while loop.
// Using break in for loop
for (...) {
if(test){
break
}
}
Kotlin – Break Statement
// Using break in while loop
while (condition) {
if(test){
break
}
}
// Using break in do...while loop
do {
if(test){
break
}
} while(condition)
Kotlin – Labeled Break Statement
Kotlin label is theform of identifier followed by the @ sign,for example test@or outer@. To makeanyKotlin Expression aslabeled
one, we justneed to putalabel infront of theexpression.
Kotlin labeled break statementis used to terminatethespecific loop. Thisis done byusing break expression with@ signfollowed by
labelname(break@LabelName).
Syntax:
outerLoop@ for (i in 1..100) {
// ...
}
Example
fun main(args: Array<String>) {
outerLoop@ for (i in 1..3) {
innerLoop@ for (j in 1..3) {
println("i = $i and j = $j")
if (i == 2){
break@outerLoop
}
}
}
}
Kotlin Continue Statement
TheKotlincontinue statementbreaks theloop iterationin between(skips thepart nextto thecontinuestatementtillend of theloop)
andcontinueswiththenext iterationin theloop.
// Using continue in for loop
for (...) {
if(test){
continue
}
}
Kotlin – Continue Statement
// Using continue in while loop
while (condition) {
if(test){
continue
}
}
// Using continue in do...while loop
do {
if(test){
continue
}
}while(condition)
Kotlin – labelled Continue
Statement
Kotlin labeled continue statement is used to skip the part of a specific loop. This is done by using continue expression with @ sign followed by label name (continue@LabelName).
fun main(args: Array<String>) {
outerLoop@ for (i in 1..3) {
innerLoop@ for (j in 1..3) {
if (i == 2){
continue@outerLoop
}
println("i = $i and j = $j")
}
}
}
QUIZ TIME!!!
Q&A Session!
Thank you! 

More Related Content

Similar to Kotlin Fundamentals for Android Development

Vizwik Coding Manual
Vizwik Coding ManualVizwik Coding Manual
Vizwik Coding ManualVizwik
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1Hossein Zahed
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#Rohit Rao
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basicsmhtspvtltd
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 

Similar to Kotlin Fundamentals for Android Development (20)

Vizwik Coding Manual
Vizwik Coding ManualVizwik Coding Manual
Vizwik Coding Manual
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Kotlin
KotlinKotlin
Kotlin
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 

Recently uploaded

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 

Kotlin Fundamentals for Android Development

  • 2. Topics :-  Introduction  KeyWords  Input Output  Data Types  Operators  Flow Controls  Functions
  • 3. INTRODUCTION TO KOTLIN Kotlin is a programming language introduced by JetBrains in 2011, the official designer of the most intelligent java ide, named Intellij Idea. Kotlin is free, has been free and will remain free. It is developed under the apache 2.0 license. This is a strongly statically typed general-purpose programming language that runs on jvm. Following are the great companies who are using Kotlin: •Google •Amazon •Netflix •Pinterest •Many more…..
  • 4. Kotlin Program Entry Point :-  Anentrypoint of a Kotlinapplication is themain()function. fun main() { var string: String = "Hello, World!" println("$string") } (or) fun main(args: Array<String>) { println("Hello, world!") }
  • 5. Kotlin - Keywords Kotlinkeywordshavebeencategorizedintothreebroadcategories:(a)HardKeywords(b) SoftKeywords(c) ModifierKeywords Kotlin Hard Keywords as as? break class continue do else false for fun if in !in interface is !is null object package return super this throw true try typealias typeof val var when while
  • 6. Kotlin - Keywords Kotlin Soft Keywords by catch constructor delegate dynamic field file finally get import init param property receiver set setparam value where Kotlin Modifier Keywords actual abstract annotation companion const crossinline data enum expect external final infix inline inner internal lateinit noinline open operator out override private protected public reified sealed suspend tailrec vararg
  • 7. Kotlin - Variables Variables are an important part of any programming. They are the names you givetocomputer memory locations which are usedto store values in a computer program and later you use those names to retrievethestoredvaluesandusetheminyourprogram.Kotlinvariablesarecreatedusingeithervar orval keywordsand thenanequalsign= isusedtoassignavaluetothosecreatedvariables. Kotlin Mutable Variables Mutablemeansthatthevariablecan bereassignedtoadifferentvalueafterinitialassignment.To declareamutablevariable,weusethevarkeyword fun main() { var name = "Zara Ali" println("Name = $name") name = "Nuha Ali" println("Name = $name") }
  • 8. Kotlin - Variables Kotlin Read-only Variables Aread-only variable can be declared using val (instead ofvar)andonce a valueis assigned, it can not bere-assigned. Kotlin Variable Naming Rules Therearecertainrulestobe followedwhile namingthe Kotlinvariables: •Kotlinvariablenamescancontainletters,digits,underscores,anddollarsigns. •Kotlinvariablenamesshouldstartwitha letter,$ orunderscores •KotlinvariablesarecasesensitivewhichmeansZaraandZARA aretwo differentvariables. •Kotlinvariablecannothaveany whitespaceorothercontrolcharacters. •Kotlinvariablecannothavenameslike var,val,String,Intbecausethey arereservedkeywordsinKotlin.
  • 9. Kotlin - Data Types Kotlin built indatatype canbe categorizedasfollows:  Number  Character  String  Boolean  Array
  • 10. (a) Kotlin Number Data Types :- Data Type Size (bits) Data Range Byte 8 bit -128 to 127 Short 16 bit -32768 to 32767 Int 32 bit -2,147,483,648 to 2,147,483,647 Long 64 bit -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 Float 32 bit 1.40129846432481707e-45 to 3.40282346638528860e+38 Double 64 bit 4.94065645841246544e-324 to 1.79769313486231570e+308
  • 11. Example :- fun main(args: Array<String>) { val a: Int = 10000 val d: Double = 100.00 val f: Float = 100.00f val l: Long = 1000000004 val s: Short = 10 val b: Byte = 1 println("Int Value is " + a) println("Double Value is " + d) println("Float Value is " + f) println("Long Value is " + l ) println("Short Value is " + s) println("Byte Value is " + b) }
  • 12. (b) Kotlin Character Data Type :- fun main(args: Array<String>) { val letter: Char // defining a Char variable letter = 'A' // Assigning a value to it println("$letter") }
  • 13. Kotlin String Data Type :- The Stringdata type is used tostore a sequence ofcharacters. String values must be surrounded by double quotes ("") ortriplequote (""" """). We have twokinds ofstring available in Kotlin- one iscalled EscapedString andanother iscalled Raw String. •Escapedstring isdeclared within double quote (" ")andmay contain escape characters like 'n', 't','b' etc. •Raw string is declared within triplequote (""" """) andmay contain multiple lines oftext without any escape characters.
  • 14. Example:- fun main(args: Array<String>) { val escapedString : String = "I am escaped String!n" var rawString :String = """This is going to be a multi-line string and will not have any escape sequence"""; print(escapedString) println(rawString) }
  • 15. Kotlin Boolean Data Type :- Boolean is very simple like other programminglanguages. We have only twovalues forBoolean data type - either true orfalse. fun main(args: Array<String>) { val A: Boolean = true // defining a variable with true value val B: Boolean = false // defining a variable with false value println("Value of variable A "+ A ) println("Value of variable B "+ B ) }
  • 16. Kotlin Array Data Type :- Kotlin arraysareacollection ofhomogeneous data.Arrays areused tostore multiple values in a single variable,instead of declaring separate variablesforeach value. fun main(args: Array<String>) { val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5) println("Value at 3rd position : " + numbers[2]) }
  • 17. Kotlin Data Type Conversion :- Typeconversionisa processinwhichthevalue ofone datatype isconvertedintoanothertype. Kotlindoesnotsupportdirectconversionofonenumericdatatype toanother, For example,itisnotpossibletoconvertanInttype to aLongtype: To convert a numeric data type to another type, Kotlin provides a set of functions:  toByte()  toShort()  toInt()  toLong()  toFloat()  toDouble()  toChar()
  • 18. Kotlin Operators Operators are the special symbols that perform different operation on operands. For example + and – are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. • Arithmetic operator • Relation operator • Assignment operator • Unary operator • Logical operator • Bitwise operator
  • 19. Arithmetic Operators Operators Meaning Expression Translate to + Addition a + b a.plus(b) – Subtraction a – b a.minus(b) * Multiplication a * b a.times(b) / Division a / b a.div(b) % Modulus a % b a.rem(b)
  • 20. Relation Operators Operators Meaning Expression Translate to > greater than a > b a.compareTo(b) > 0 < less than a < b a.compareTo(b) < 0 >= greater than or equal to a >= b a.compareTo(b) >= 0 <= less than or equal to a <= b a.compareTo(b) <= 0 == is equal to a == b a?.equals(b) ?: (b === null) != not equal to a != b !(a?.equals(b) ?: (b === null)) > 0
  • 21. Assignment Operators Operators Expression Translate to += a = a + b a.plusAssign(b) > 0 -= a = a – b a.minusAssign(b) < 0 *= a = a * b a.timesAssign(b)>= 0 /= a = a / b a.divAssign(b) <= 0 %= a = a % b a.remAssign(b)
  • 22. Unary Operators Operators Expression Translate to ++ ++a or a++ a.inc() — –a or a– a.dec()
  • 23. Logical Operators Operators Meaning Expression && return true if all expressions are true (a>b) && (a>c) || return true if any of expression is true (a>b) || (a>c) ! return complement of the expression a.not()
  • 24. Bitwise Operators Operators Meaning Expression shl signed shift left a.shl(b) shr signed shift right a.shr(b) ushr unsigned shift right a.ushr() and bitwise and a.and(b) or bitwise or a.or() xor bitwise xor a.xor() inv bitwise inverse a.inv()
  • 25. Kotlin Control Flow Statements :- Kotlin flow control statements determine the next statement tobe executed. For example,  if  if – else  when  while  for  do
  • 26. Kotlin if...else Expression Kotlin if...else canalso be used asanexpression whichreturnsa valueand thisvaluecanbe assigned to avariable.Below is a simple syntaxof Kotlinif...else expression: val result = if (condition) { // code block A to be executed if condition is true } else { // code block B to be executed if condition is false }
  • 27. Example fun main(args: Array<String>) { val age:Int = 10 val result = if (age > 18) { "Adult" } else { "Minor" } println(result) }
  • 28. Kotlin when expression when expression is far easy and more clean in comparison to writing many if...else if expressions. Kotlin when expression evaluates a sectionof code among manyalternativesasexplained in below example. Kotlin when matchesits argumentagainstall branchessequentiallyuntilsome branchcondition is satisfied. Kotlin when expression is similar to the switch statementin C, C++ and Java.
  • 29. Example 1 fun main(args: Array<String>) { val day = 2 val result = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid day." } println(result) }
  • 30. Example 2 We cancombine multiple when conditions into asingle condition. fun main(args: Array<String>) { val day = 2 when (day) { 1, 2, 3, 4, 5 -> println("Weekday") else -> println("Weekend") } }
  • 31. Example 3 Kotlin rangesarecreatedusing double dots .. andwe canusethem while checking when condition withthehelpof inoperator. fun main(args: Array<String>) { val day = 2 when (day) { in 1..5 -> println("Weekday") else -> println("Weekend") } }
  • 32. Kotlin For loop Kotlin forloop iteratesthroughanythingthatprovides aniterator ie. thatcontainsa countablenumber of values,for example arrays, ranges,maps or anyother collection availablein Kotlin. Kotlin does notprovide a conventionalforloop whichis available inC, C++ andJavaetc. Syntax Thesyntaxof theKotlin forloop is asfollows: for (item in collection) { // body of loop }
  • 33. Example 1 Following is anexample wheretheloop iteratesthroughthe rangeandprintsindividual item. To iterateover a rangeof numbers, we willuse arangeexpression: fun main(args: Array<String>) { for (item in 1..5) { println(item) } }
  • 34. Example 2 Let's seeone more example wheretheloop williteratethroughanotherrange,but thistime it willstep down insteadof stepping up asin theabove example: fun main(args: Array<String>) { for (item in 5 downTo 1 step 2) { println(item) } }
  • 35. Example 3 Following is anexample wherewe used forloop to iteratethroughanarrayof strings: fun main(args: Array<String>) { var fruits = arrayOf("Orange", "Apple", "Mango", "Banana") for (item in fruits) { println(item) } }
  • 36. Kotlin – while loop Kotlin whileloop executes itsbody continuouslyaslong asthespecified condition is true. Kotlin whileloop is similar to Java while loop. Syntax : Thesyntaxof theKotlin whileloop is asfollows: while (condition) { // body of the loop }
  • 37. Example Following is anexample wherethewhile loop continueexecuting thebody of theloop aslong asthecountervariable i is greaterthan0: fun main(args: Array<String>) { var i = 5; while (i > 0) { println(i) i– } }
  • 38. Kotlin – do … while loop Thedo..while is similar to the while loop with a difference that the this loop will execute the code block once,before checkingif the condition is true,then it will repeat the loop as long as the condition is true. Theloop will always be executed at least once, even if the condition is false, because the code block is executedbefore the condition is tested. Syntax: Thesyntax of theKotlin do...while loop is as follows: do{ // body of the loop }while( condition )
  • 39. Example Following is anexample wherethedo...while loop continueexecutingthe body of the loop as long asthecountervariable i is greater than0: fun main(args: Array<String>) { var i = 5; do{ println(i) i– }while(i > 0) }
  • 40. Kotlin – Break Statement Kotlin breakstatement is usedto come out of a loop once a certain condition is met. This loop could bea for, while ordo...while loop. // Using break in for loop for (...) { if(test){ break } }
  • 41. Kotlin – Break Statement // Using break in while loop while (condition) { if(test){ break } } // Using break in do...while loop do { if(test){ break } } while(condition)
  • 42. Kotlin – Labeled Break Statement Kotlin label is theform of identifier followed by the @ sign,for example test@or outer@. To makeanyKotlin Expression aslabeled one, we justneed to putalabel infront of theexpression. Kotlin labeled break statementis used to terminatethespecific loop. Thisis done byusing break expression with@ signfollowed by labelname(break@LabelName). Syntax: outerLoop@ for (i in 1..100) { // ... }
  • 43. Example fun main(args: Array<String>) { outerLoop@ for (i in 1..3) { innerLoop@ for (j in 1..3) { println("i = $i and j = $j") if (i == 2){ break@outerLoop } } } }
  • 44. Kotlin Continue Statement TheKotlincontinue statementbreaks theloop iterationin between(skips thepart nextto thecontinuestatementtillend of theloop) andcontinueswiththenext iterationin theloop. // Using continue in for loop for (...) { if(test){ continue } }
  • 45. Kotlin – Continue Statement // Using continue in while loop while (condition) { if(test){ continue } } // Using continue in do...while loop do { if(test){ continue } }while(condition)
  • 46. Kotlin – labelled Continue Statement Kotlin labeled continue statement is used to skip the part of a specific loop. This is done by using continue expression with @ sign followed by label name (continue@LabelName). fun main(args: Array<String>) { outerLoop@ for (i in 1..3) { innerLoop@ for (j in 1..3) { if (i == 2){ continue@outerLoop } println("i = $i and j = $j") } } }
  • 47.