SlideShare a Scribd company logo
& 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 (20)

PDF
A quick and fast intro to Kotlin
XPeppers
 
PDF
Kotlin for Android Development
Speck&Tech
 
PPTX
Intro to kotlin
Tomislav Homan
 
PPT
SQLITE Android
Sourabh Sahu
 
PDF
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
PPTX
Kotlin on android
Kurt Renzo Acosta
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PDF
Data Persistence in Android with Room Library
Reinvently
 
PPTX
Android User Interface
Shakib Hasan Sumon
 
PPTX
Kotlin presentation
MobileAcademy
 
PPTX
Kotlin
YeldosTanikin
 
PDF
JavaScript: Variables and Functions
Jussi Pohjolainen
 
PPTX
SQLite database in android
Gourav Kumar Saini
 
PPSX
Junit
FAROOK Samath
 
PPTX
Fragment
nationalmobileapps
 
PPT
Introduction to Android Fragments
Sergi Martínez
 
PDF
Kotlin vs Java | Edureka
Edureka!
 
PPT
The Kotlin Programming Language
intelliyole
 
PPTX
Cross platform app development with flutter
Hwan Jo
 
PPTX
Android Services
Ahsanul Karim
 
A quick and fast intro to Kotlin
XPeppers
 
Kotlin for Android Development
Speck&Tech
 
Intro to kotlin
Tomislav Homan
 
SQLITE Android
Sourabh Sahu
 
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Kotlin on android
Kurt Renzo Acosta
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Data Persistence in Android with Room Library
Reinvently
 
Android User Interface
Shakib Hasan Sumon
 
Kotlin presentation
MobileAcademy
 
JavaScript: Variables and Functions
Jussi Pohjolainen
 
SQLite database in android
Gourav Kumar Saini
 
Introduction to Android Fragments
Sergi Martínez
 
Kotlin vs Java | Edureka
Edureka!
 
The Kotlin Programming Language
intelliyole
 
Cross platform app development with flutter
Hwan Jo
 
Android Services
Ahsanul Karim
 

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

PDF
Kotlin for Android devs
Adit Lal
 
PDF
Kotlin what_you_need_to_know-converted event 4 with nigerians
junaidhasan17
 
PDF
Little Helpers for Android Development with Kotlin
Kai Koenig
 
PDF
Basics of kotlin ASJ
DSCBVRITH
 
PPTX
Kotlin as a Better Java
Garth Gilmour
 
PDF
Kotlin for Android Developers - 3
Mohamed Nabil, MSc.
 
PDF
Introduction to Kotlin - Android KTX
Syed Awais Mazhar Bukhari
 
PPTX
Introduction to Kotlin for Android developers
Mohamed Wael
 
PDF
Intro to Kotlin
Magda Miu
 
PDF
Kotlin: A pragmatic language by JetBrains
Jigar Gosar
 
PDF
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
PDF
Exploring Kotlin
Johan Haleby
 
PPTX
Unit 1 part for information technology 1.pptx
shambelworku8
 
PPTX
Hello to Kotlin
FatimaYousif11
 
PPTX
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
PDF
Practical tips for building apps with kotlin
Adit Lal
 
PPTX
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
PDF
Privet Kotlin (Windy City DevFest)
Cody Engel
 
PDF
Save time with kotlin in android development
Adit Lal
 
Kotlin for Android devs
Adit Lal
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
junaidhasan17
 
Little Helpers for Android Development with Kotlin
Kai Koenig
 
Basics of kotlin ASJ
DSCBVRITH
 
Kotlin as a Better Java
Garth Gilmour
 
Kotlin for Android Developers - 3
Mohamed Nabil, MSc.
 
Introduction to Kotlin - Android KTX
Syed Awais Mazhar Bukhari
 
Introduction to Kotlin for Android developers
Mohamed Wael
 
Intro to Kotlin
Magda Miu
 
Kotlin: A pragmatic language by JetBrains
Jigar Gosar
 
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
Exploring Kotlin
Johan Haleby
 
Unit 1 part for information technology 1.pptx
shambelworku8
 
Hello to Kotlin
FatimaYousif11
 
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
Practical tips for building apps with kotlin
Adit Lal
 
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
Privet Kotlin (Windy City DevFest)
Cody Engel
 
Save time with kotlin in android development
Adit Lal
 
Ad

Recently uploaded (20)

PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PDF
NTPC PATRATU Summer internship report.pdf
hemant03701
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PPTX
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
Alan Turing - life and importance for all of us now
Pedro Concejero
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PPT
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PPTX
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
NTPC PATRATU Summer internship report.pdf
hemant03701
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Alan Turing - life and importance for all of us now
Pedro Concejero
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
Ad

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