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

What's hot (20)

Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Kotlin Language powerpoint show file
Kotlin Language powerpoint show fileKotlin Language powerpoint show file
Kotlin Language powerpoint show file
 
Android Development with Kotlin course
Android Development  with Kotlin courseAndroid Development  with Kotlin course
Android Development with Kotlin course
 
Kotlin
KotlinKotlin
Kotlin
 
Introduction to Flutter
Introduction to FlutterIntroduction to Flutter
Introduction to Flutter
 
Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
 
C# basics
 C# basics C# basics
C# basics
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptx
 
Google flutter the easy and practical way
Google flutter the easy and practical wayGoogle flutter the easy and practical way
Google flutter the easy and practical way
 
Android with kotlin course
Android with kotlin courseAndroid with kotlin course
Android with kotlin course
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - Introduction
 
flutter.school #HelloWorld
flutter.school #HelloWorldflutter.school #HelloWorld
flutter.school #HelloWorld
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Performance optimization for Android
Performance optimization for AndroidPerformance optimization for Android
Performance optimization for Android
 

Similar to Introduction to Koltin for Android Part I

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
junaidhasan17
 

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

Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
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
 

Recently uploaded

+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
Health
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
"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
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
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
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 

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
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
"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"
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
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
 
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.!!