SlideShare a Scribd company logo
1 of 38
& Android
Android Best Practices and Advance Kotlin
Kotlin and Android 1
About Me
• Muhammad Atif
• Work at Telenor
• My favorite language is Java & Kotlin
• Love Hiking
Kotlin and Android 2
Table of Content
Basic Syntax
Advance Kotlin
Android Best Pratices
Kotlin and Android 3
What Kotlin is Not
Kotlin and Android 4
Kotlin programming language, design goals
• Concise:
• Reduce the amount of code
• Safe
• No more NullPointerExceptions
• Val name = data?.getStringExtra(NAME)
• Interoperable
• Use existing libraries for JVM (like Android API)
• Compile to JVM or JavaScript
• Tool-friendly
• Support for the programmer using editors (like Android Studio)
Kotlin and Android 5
Kotlin, a little syntax
• Semicolons are optional
• Adding a new-line is generally enough
• Variables and constants
• var name = ”Atif” // variable
• var means ”variable”
• val name2 = ” Atif” // read-only (constant)
• val means ”value”
• Types are not specified explicity by the programmer
• Types are infered by the compiler
Kotlin and Android 6
• var
• val
• lateinit
• lazy
• getters
• setters
Kotlin and Android 7
Data types , variable declaration and initialization
• Mutable.
• non-final variables.
• Once initialized, we’re free to
mutate/change the data held by
the variable.
For example, in Kotlin:
var myVariable = 1
• read-only/nonmutable/imutable.
• The use of val is like declaring a
new variable in Java with
the final keyword.
For example, in Kotlin:
val name: String = "Kotlin"
Kotlin and Android 8
Difference b/w var & val Kotlin’s keyword .
• lateinit means late initialization.
• If you do not want to initialize a
variable in the constructor instead
you want to initialize it later
• if you can guarantee the initialization
before using it, then declare that
variable with lateinit keyword.
• It will not allocate memory until
initialized.
• It means lazy initialization.
• Your variable will not be
initialized unless you use that
variable in your code.
• It will be initialized only once
after that we always use the same
value.
Kotlin and Android 9
How Kotlin Keywords & delegate,
Lateinit & Lazy works?
setters are used for setting value of
the property. Kotlin internally
generates a
default getter and setter for
mutable properties using var.
Property type is optional if it can be
inferred from the initializer.
set(value)
getters are used for getting value of
the property. Kotlin internally
generates a getter for read-only
properties using val. The getter is
optional in kotlin. Property type is
optional if it can be inferred from
the initializer.
get() = value
Kotlin and Android 10
How Kotlin Properties,getter &
setter works?
Kotlin and Android 11
Nullable Types and Null Safety in
Kotlin
• Kotlin supports nullability as part of its type System. That means
You have the ability to declare whether a variable can hold a null
value or not.
• By supporting nullability in the type system, the compiler can
detect possible NullPointerException errors at compile time and
reduce the possibility of having them thrown at runtime.
var greeting: String = "Hello, World"
greeting = null // Compilation Error
• To allow null values, you have to declare a variable as nullable by
appending a question mark in its type declaration -
var nullableGreeting: String? = "Hello, World“
nullableGreeting = null // Works
Safety Checks
• Adding is initialized check
if (::name.isInitialized)
• Adding a null Check
• Safe call operator: ?
val name = if(null != nullableName)
nullableName else "Guest“
• Elvis operator: ‘ ?: ’
val b = a?.length ?: -1
• Not null assertion : !! Operator
• Nullability Annotations
@NotNull
Kotlin and Android 12
Nullability and Collections
• Kotlin’s collection API is built on top of Java’s collection API
but it fully supports nullability on Collections.
Just as regular variables are non-null by default,
a normal collection also can’t hold null values.
val regularList: List<Int> = listOf(1, 2, null, 3) // Compiler Error
• Collection of Nullable Types
val listOfNullableTypes: List<Int?>
= listOf(1, 2, null, 3) // Works
• To filter non-null values from a list of nullable types, you
can use the filterNotNull() function .
val notNullList: List<Int> =listOfNullableTypes.filterNotNull()
var listOfNullableTypes: List<Int?>
= listOf(1, 2, null, 3) // Works
listOfNullableTypes = null // Compilation Error
var nullableList: List<Int>?
= listOf(1, 2, 3) nullableList = null // Works
var nullableListOfNullableTypes: List<Int?>?
= listOf(1, 2, null, 3) // Works
nullableListOfNullableTypes = null // Works
Kotlin and Android 13
Kotlin Operators
Just like other languages, Kotlin provides various
operators to perform computations on numbers.
• Arithmetic operators (+, -, *, /, %)
• Comparison operators (==, !=, <, >, <=, >=)
• Assignment operators (+=, -=, *=, /=, %=)
• Increment & Decrement operators (++, --)
Operations on Numeric Types
Expression Translates to
a + b a.plus(b)
a - b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b a.rem(b)
a++ a.inc()
a−− a.dec()
a > b
a.compareTo(b)
> 0
a < b
a.compareTo(b)
< 0
a += b a.plusAssign(b)
Kotlin and Android 14
Kotlin Control Flow
• If-Else Statement
• When Expression(Switch)
• For Loop
• For Each Loop
• While Loop
• do-while loop
• Break and Continue
Kotlin and Android 15
Kotlin Functions
• Unit returning Functions
Functions which don’t return anything has a return type of Unit.
The Unit type corresponds to void in Java.
fun printAverage(a: Double, b: Double): Unit {
println("Avg of ($a, $b) = ${(a + b)/2}")
}
• Single Expression Functions
fun avg(a: Double, b: Double): Double { return (a + b)/2 }
avg(4.6, 9.0) // 6.8
Kotlin and Android 16
Kotlin Functions
• Defining and Calling Functions
You can declare a function in Kotlin using the fun keyword.
Following is a simple function that calculates the average of
two numbers .
Syntax:
fun functionName(param1: Type1, param2: Type2,...,
paramN: TypeN): Type {
// Method Body
}
For Example:
fun avg(a: Double, b: Double): Double { return (a + b)/2 }
avg(4.6, 9.0) // 6.8
Kotlin and Android 17
Kotlin extensions/ Utility Functions
add new function to the classes.
• Can add new function to class without declaring it.
• The new function added behaves like static
• Extensions can become part of your own classes &
predefined classes.
Example:
val firstName=“hello”
val secondName=“hello”
val thirdName=“hello”
fun String.add(firstname :String,secondName:String){
retrun this + firstName+secondName;
}
Kotlin and Android 18
Kotlin infix Functions
Infix function can be a member function or extension function.
Properties :
• They have single parameter.
• They have prefix of infix.
For example:
infix fun Int.greaterValue(other:Int):Int {
If(this>other){
return this
}else{
return other
}}
val greaterVal= x greaterValue y
Kotlin and Android 19
Kotlin tailRec[recursive] Functions
Uses recursion in a optimized way.
• Prevents stack over flow exception.
• Prefix of tailrec is used.
For example:
tailrec fun getFibonacciNumber(n: Int, a: BigInteger, b:
BigInteger): BigInteger {
if (n == 0)
return b
}else{
return getFibonacciNumber(n - 1, a + b, a)
}
Kotlin and Android 20
Object Oriented Kotlin for Android
Classes
• data class User(var name:String,var age:Int)
• Compiler generate getters and setters for java
Interoperability .
• Compiler generate equal() and hashCode().
• Compiler generate copy() method –flexible clone()
replacement.
Kotlin and Android 21
Object Oriented Kotlin for Android
Classes
Example :
var user1= User(“name1”,10)
var user2=User=(“name1”,10)
If(user1==user2){
println(“equal”)
}else{
println(“not equal”)
}
var newUser=user1.copy()//.copy(name=“name”)
Kotlin and Android 22
Object Oriented Kotlin for Android
Primary Constructor
• Init block
• Primary constructor with property
• Primary constructor with parameter.
For Example :
data class User(var name:String,var age:Int)
Kotlin and Android 23
Object Oriented Kotlin for Android
Secondary Constructor
• Init block.
• Keyword constructor.
• Can not declare properties in secondary constructor.
For Example :
data class User(var name:String){
constructor(n:String,id :Int): this(n){
//body
}
}
Kotlin and Android 24
Object Oriented Kotlin for Android
• primary constructor with param
class Student1(name:String){
init{
println("name of student : ${name}")
}
}
• primary constructor
class Student(var name:String){
init{
println("name of student : ${name}")
}
}
• primary & secondary constructor
class User(var name:String){
init{
println("name of student : ${name}")
}
constructor(n:String,id :Int): this(n){
//body
}
}
Kotlin and Android 25
Object Oriented Kotlin for Android
Inheritance
• default classes are public .
• final
for inheritance you need to make class ‘open’ in
koltin .
Child classes or derived classes.
Kotlin and Android 26
Object Oriented Kotlin for Android
Inheritance
• Single level Inheritance
• Multi Level inheritance
• Hierarchical inheritance
Kotlin and Android 27
Visibility modifier in Kotlin
Kotlin Supports
• Public
• Private
• Internal
• protected
Kotlin and Android 28
abstract Class, Methods & Properties
Classes can be abstract in Nature.
• abstract key is by default open in nature.
• Abstract class is partially defined class
• Abstract method have no body when
declared
• Abstract property can not be initialized when
declared.
• You can not create instance of abstract class
• You need to override abstract properties &
method in derived class.
Kotlin and Android 29
Interfaces in Kotlin
Listeners ,call back , services in koltin.
• Interface keyword Is used .
• Short or temporary service.
• Whatever you define in interface is by default abstract
in nature.
• You need to override abstract properties & method in
derived class.
• Interface can contains normal and abstract methods.
Kotlin and Android 30
Object Declaration and companion Objects
WHAT IS SINGLETON IN KOTLIN.?
• One INSTANCE of class in whole application.
• Single object will be created internally.
• We can not declare “static” variable or objects in kotlin as
compared to java.
• Declare “object”.
• This will create a singleton object for us when programs
runs.
• We can have properties , methods, initializers
• Can not have constructor. i:e we can not create instance
manually.
• Object can have super class, supports inheritance.
Kotlin and Android 31
Object Declaration and companion Objects
Example:
Object Customer{
init{
}
var id:Int=0
fun getId():Integer{
return id;
}
}
Kotlin and Android 32
Object Declaration and companion Objects
Companion Objects.
• Same as object but declared within a particular class.
Example:
Class MyClass{
companion object {
var count:Id=1
fun voidFun(){//body}
}
}
Kotlin and Android 33
Using the Data Binding Library
Data Binding
• automatically generates the classes required to bind the
views in the layout with your data objects.
• One way data binding.
• Two way data binding.
Kotlin and Android 34
Using the Data Binding Library
1 way vs. two way Data Binding
• One-way data-binding means the data flows
in a single direction so that whenever the
data changes in a component, it also
updates the view with new data.
• Two-way data binding means data flows in
both directions, it means any change
happens in the view updates the data and
any change happens in the data updates the
view.
Kotlin: no more findViewById(…)
• Import kotlinx.android.synthetic.main.activity_main.*
• activity_main.xml is the name of the layout file
• var word = mainWordEditText.text
• mainWordEditText is the id from the layout file
• mainClearWordsButton.setOnClickListener { /*do something*/ }
• mainClearWordsButton is the id from the layout file
Kotlin and Android 35
Android Development Best Practices
Here are some additional best practices you should follow when building Android apps:
• Use the recommended Android architecture.
• Always maintain the code quality.
• Create separate layouts for UI elements that will be re-used.
• Detecting and fixing memory leaks in android.
• Always include unit tests.
• Always include functional UI tests.
Kotlin and Android 36
Android Development Best Practices
• Avoid deep levels in layouts.
• Use the Parcelable class instead of Serializable when passing data in
Intents or Bundles.
• Perform file operations off the UI thread.
Kotlin and Android 37
Kotlin and Android 38
Advance Kotlin for Android
• Clean Architecture using MVVM
• Design Patterns
• RXJava2
• Dagger2( Dependency Injection)
• Retrofit
• DataBinding(Google)
• Clean Architecture using MVVM/MVI
• Coroutines /Flow/LiveData
• Koin ( Dependency Injection)
• Retrofit
• DataBinding (Synthetic Kotlin)
PART 2 PART 3
To be continued.!!

More Related Content

What's hot

Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Simplilearn
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | EdurekaEdureka!
 
Try Jetpack Compose
Try Jetpack ComposeTry Jetpack Compose
Try Jetpack ComposeLutasLin
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin OverviewEkta Raj
 
Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidNelson Glauber Leal
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net frameworkArun Prasad
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for androidInnovationM
 
Android Development with Kotlin course
Android Development  with Kotlin courseAndroid Development  with Kotlin course
Android Development with Kotlin courseGoogleDevelopersLeba
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling sharqiyem
 

What's hot (20)

Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
 
Kotlin
KotlinKotlin
Kotlin
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
 
Try Jetpack Compose
Try Jetpack ComposeTry Jetpack Compose
Try Jetpack Compose
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Kotlin
KotlinKotlin
Kotlin
 
Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on Android
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for android
 
Android Development with Kotlin course
Android Development  with Kotlin courseAndroid Development  with Kotlin course
Android Development with Kotlin course
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 

Similar to Introduction to Koltin for Android Part I

Basics of kotlin ASJ
Basics of kotlin ASJBasics of kotlin ASJ
Basics of kotlin ASJDSCBVRITH
 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptxadityakale2110
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlinZoran Stanimirovic
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveAndré Oriani
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigeriansjunaidhasan17
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
MOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptxMOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptxkamalkantmaurya1
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with AndroidKurt Renzo Acosta
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Dear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans tooDear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans tooVivek Chanddru
 
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
 
2#Kotlin programming tutorials(data types and hello world)
2#Kotlin programming tutorials(data types and hello world)2#Kotlin programming tutorials(data types and hello world)
2#Kotlin programming tutorials(data types and hello world)Naveen Davis
 

Similar to Introduction to Koltin for Android Part I (20)

Basics of kotlin ASJ
Basics of kotlin ASJBasics of kotlin ASJ
Basics of kotlin ASJ
 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptx
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigerians
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
MOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptxMOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptx
 
moocs_ppt.pptx
moocs_ppt.pptxmoocs_ppt.pptx
moocs_ppt.pptx
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Fall in love with Kotlin
Fall in love with KotlinFall in love with Kotlin
Fall in love with Kotlin
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Dear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans tooDear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans too
 
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
 
2#Kotlin programming tutorials(data types and hello world)
2#Kotlin programming tutorials(data types and hello world)2#Kotlin programming tutorials(data types and hello world)
2#Kotlin programming tutorials(data types and hello world)
 

Recently uploaded

Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxNadaHaitham1
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEselvakumar948
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxchumtiyababu
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersMairaAshraf6
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 

Recently uploaded (20)

Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 

Introduction to Koltin for Android Part I

  • 1. & Android Android Best Practices and Advance Kotlin Kotlin and Android 1
  • 2. About Me • Muhammad Atif • Work at Telenor • My favorite language is Java & Kotlin • Love Hiking Kotlin and Android 2
  • 3. Table of Content Basic Syntax Advance Kotlin Android Best Pratices Kotlin and Android 3
  • 4. What Kotlin is Not Kotlin and Android 4
  • 5. Kotlin programming language, design goals • Concise: • Reduce the amount of code • Safe • No more NullPointerExceptions • Val name = data?.getStringExtra(NAME) • Interoperable • Use existing libraries for JVM (like Android API) • Compile to JVM or JavaScript • Tool-friendly • Support for the programmer using editors (like Android Studio) Kotlin and Android 5
  • 6. Kotlin, a little syntax • Semicolons are optional • Adding a new-line is generally enough • Variables and constants • var name = ”Atif” // variable • var means ”variable” • val name2 = ” Atif” // read-only (constant) • val means ”value” • Types are not specified explicity by the programmer • Types are infered by the compiler Kotlin and Android 6
  • 7. • var • val • lateinit • lazy • getters • setters Kotlin and Android 7 Data types , variable declaration and initialization
  • 8. • Mutable. • non-final variables. • Once initialized, we’re free to mutate/change the data held by the variable. For example, in Kotlin: var myVariable = 1 • read-only/nonmutable/imutable. • The use of val is like declaring a new variable in Java with the final keyword. For example, in Kotlin: val name: String = "Kotlin" Kotlin and Android 8 Difference b/w var & val Kotlin’s keyword .
  • 9. • lateinit means late initialization. • If you do not want to initialize a variable in the constructor instead you want to initialize it later • if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. • It will not allocate memory until initialized. • It means lazy initialization. • Your variable will not be initialized unless you use that variable in your code. • It will be initialized only once after that we always use the same value. Kotlin and Android 9 How Kotlin Keywords & delegate, Lateinit & Lazy works?
  • 10. setters are used for setting value of the property. Kotlin internally generates a default getter and setter for mutable properties using var. Property type is optional if it can be inferred from the initializer. set(value) getters are used for getting value of the property. Kotlin internally generates a getter for read-only properties using val. The getter is optional in kotlin. Property type is optional if it can be inferred from the initializer. get() = value Kotlin and Android 10 How Kotlin Properties,getter & setter works?
  • 11. Kotlin and Android 11 Nullable Types and Null Safety in Kotlin • Kotlin supports nullability as part of its type System. That means You have the ability to declare whether a variable can hold a null value or not. • By supporting nullability in the type system, the compiler can detect possible NullPointerException errors at compile time and reduce the possibility of having them thrown at runtime. var greeting: String = "Hello, World" greeting = null // Compilation Error • To allow null values, you have to declare a variable as nullable by appending a question mark in its type declaration - var nullableGreeting: String? = "Hello, World“ nullableGreeting = null // Works Safety Checks • Adding is initialized check if (::name.isInitialized) • Adding a null Check • Safe call operator: ? val name = if(null != nullableName) nullableName else "Guest“ • Elvis operator: ‘ ?: ’ val b = a?.length ?: -1 • Not null assertion : !! Operator • Nullability Annotations @NotNull
  • 12. Kotlin and Android 12 Nullability and Collections • Kotlin’s collection API is built on top of Java’s collection API but it fully supports nullability on Collections. Just as regular variables are non-null by default, a normal collection also can’t hold null values. val regularList: List<Int> = listOf(1, 2, null, 3) // Compiler Error • Collection of Nullable Types val listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works • To filter non-null values from a list of nullable types, you can use the filterNotNull() function . val notNullList: List<Int> =listOfNullableTypes.filterNotNull() var listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works listOfNullableTypes = null // Compilation Error var nullableList: List<Int>? = listOf(1, 2, 3) nullableList = null // Works var nullableListOfNullableTypes: List<Int?>? = listOf(1, 2, null, 3) // Works nullableListOfNullableTypes = null // Works
  • 13. Kotlin and Android 13 Kotlin Operators Just like other languages, Kotlin provides various operators to perform computations on numbers. • Arithmetic operators (+, -, *, /, %) • Comparison operators (==, !=, <, >, <=, >=) • Assignment operators (+=, -=, *=, /=, %=) • Increment & Decrement operators (++, --) Operations on Numeric Types Expression Translates to a + b a.plus(b) a - b a.minus(b) a * b a.times(b) a / b a.div(b) a % b a.rem(b) a++ a.inc() a−− a.dec() a > b a.compareTo(b) > 0 a < b a.compareTo(b) < 0 a += b a.plusAssign(b)
  • 14. Kotlin and Android 14 Kotlin Control Flow • If-Else Statement • When Expression(Switch) • For Loop • For Each Loop • While Loop • do-while loop • Break and Continue
  • 15. Kotlin and Android 15 Kotlin Functions • Unit returning Functions Functions which don’t return anything has a return type of Unit. The Unit type corresponds to void in Java. fun printAverage(a: Double, b: Double): Unit { println("Avg of ($a, $b) = ${(a + b)/2}") } • Single Expression Functions fun avg(a: Double, b: Double): Double { return (a + b)/2 } avg(4.6, 9.0) // 6.8
  • 16. Kotlin and Android 16 Kotlin Functions • Defining and Calling Functions You can declare a function in Kotlin using the fun keyword. Following is a simple function that calculates the average of two numbers . Syntax: fun functionName(param1: Type1, param2: Type2,..., paramN: TypeN): Type { // Method Body } For Example: fun avg(a: Double, b: Double): Double { return (a + b)/2 } avg(4.6, 9.0) // 6.8
  • 17. Kotlin and Android 17 Kotlin extensions/ Utility Functions add new function to the classes. • Can add new function to class without declaring it. • The new function added behaves like static • Extensions can become part of your own classes & predefined classes. Example: val firstName=“hello” val secondName=“hello” val thirdName=“hello” fun String.add(firstname :String,secondName:String){ retrun this + firstName+secondName; }
  • 18. Kotlin and Android 18 Kotlin infix Functions Infix function can be a member function or extension function. Properties : • They have single parameter. • They have prefix of infix. For example: infix fun Int.greaterValue(other:Int):Int { If(this>other){ return this }else{ return other }} val greaterVal= x greaterValue y
  • 19. Kotlin and Android 19 Kotlin tailRec[recursive] Functions Uses recursion in a optimized way. • Prevents stack over flow exception. • Prefix of tailrec is used. For example: tailrec fun getFibonacciNumber(n: Int, a: BigInteger, b: BigInteger): BigInteger { if (n == 0) return b }else{ return getFibonacciNumber(n - 1, a + b, a) }
  • 20. Kotlin and Android 20 Object Oriented Kotlin for Android Classes • data class User(var name:String,var age:Int) • Compiler generate getters and setters for java Interoperability . • Compiler generate equal() and hashCode(). • Compiler generate copy() method –flexible clone() replacement.
  • 21. Kotlin and Android 21 Object Oriented Kotlin for Android Classes Example : var user1= User(“name1”,10) var user2=User=(“name1”,10) If(user1==user2){ println(“equal”) }else{ println(“not equal”) } var newUser=user1.copy()//.copy(name=“name”)
  • 22. Kotlin and Android 22 Object Oriented Kotlin for Android Primary Constructor • Init block • Primary constructor with property • Primary constructor with parameter. For Example : data class User(var name:String,var age:Int)
  • 23. Kotlin and Android 23 Object Oriented Kotlin for Android Secondary Constructor • Init block. • Keyword constructor. • Can not declare properties in secondary constructor. For Example : data class User(var name:String){ constructor(n:String,id :Int): this(n){ //body } }
  • 24. Kotlin and Android 24 Object Oriented Kotlin for Android • primary constructor with param class Student1(name:String){ init{ println("name of student : ${name}") } } • primary constructor class Student(var name:String){ init{ println("name of student : ${name}") } } • primary & secondary constructor class User(var name:String){ init{ println("name of student : ${name}") } constructor(n:String,id :Int): this(n){ //body } }
  • 25. Kotlin and Android 25 Object Oriented Kotlin for Android Inheritance • default classes are public . • final for inheritance you need to make class ‘open’ in koltin . Child classes or derived classes.
  • 26. Kotlin and Android 26 Object Oriented Kotlin for Android Inheritance • Single level Inheritance • Multi Level inheritance • Hierarchical inheritance
  • 27. Kotlin and Android 27 Visibility modifier in Kotlin Kotlin Supports • Public • Private • Internal • protected
  • 28. Kotlin and Android 28 abstract Class, Methods & Properties Classes can be abstract in Nature. • abstract key is by default open in nature. • Abstract class is partially defined class • Abstract method have no body when declared • Abstract property can not be initialized when declared. • You can not create instance of abstract class • You need to override abstract properties & method in derived class.
  • 29. Kotlin and Android 29 Interfaces in Kotlin Listeners ,call back , services in koltin. • Interface keyword Is used . • Short or temporary service. • Whatever you define in interface is by default abstract in nature. • You need to override abstract properties & method in derived class. • Interface can contains normal and abstract methods.
  • 30. Kotlin and Android 30 Object Declaration and companion Objects WHAT IS SINGLETON IN KOTLIN.? • One INSTANCE of class in whole application. • Single object will be created internally. • We can not declare “static” variable or objects in kotlin as compared to java. • Declare “object”. • This will create a singleton object for us when programs runs. • We can have properties , methods, initializers • Can not have constructor. i:e we can not create instance manually. • Object can have super class, supports inheritance.
  • 31. Kotlin and Android 31 Object Declaration and companion Objects Example: Object Customer{ init{ } var id:Int=0 fun getId():Integer{ return id; } }
  • 32. Kotlin and Android 32 Object Declaration and companion Objects Companion Objects. • Same as object but declared within a particular class. Example: Class MyClass{ companion object { var count:Id=1 fun voidFun(){//body} } }
  • 33. Kotlin and Android 33 Using the Data Binding Library Data Binding • automatically generates the classes required to bind the views in the layout with your data objects. • One way data binding. • Two way data binding.
  • 34. Kotlin and Android 34 Using the Data Binding Library 1 way vs. two way Data Binding • One-way data-binding means the data flows in a single direction so that whenever the data changes in a component, it also updates the view with new data. • Two-way data binding means data flows in both directions, it means any change happens in the view updates the data and any change happens in the data updates the view.
  • 35. Kotlin: no more findViewById(…) • Import kotlinx.android.synthetic.main.activity_main.* • activity_main.xml is the name of the layout file • var word = mainWordEditText.text • mainWordEditText is the id from the layout file • mainClearWordsButton.setOnClickListener { /*do something*/ } • mainClearWordsButton is the id from the layout file Kotlin and Android 35
  • 36. Android Development Best Practices Here are some additional best practices you should follow when building Android apps: • Use the recommended Android architecture. • Always maintain the code quality. • Create separate layouts for UI elements that will be re-used. • Detecting and fixing memory leaks in android. • Always include unit tests. • Always include functional UI tests. Kotlin and Android 36
  • 37. Android Development Best Practices • Avoid deep levels in layouts. • Use the Parcelable class instead of Serializable when passing data in Intents or Bundles. • Perform file operations off the UI thread. Kotlin and Android 37
  • 38. Kotlin and Android 38 Advance Kotlin for Android • Clean Architecture using MVVM • Design Patterns • RXJava2 • Dagger2( Dependency Injection) • Retrofit • DataBinding(Google) • Clean Architecture using MVVM/MVI • Coroutines /Flow/LiveData • Koin ( Dependency Injection) • Retrofit • DataBinding (Synthetic Kotlin) PART 2 PART 3 To be continued.!!