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

More Related Content

What's hot (20)

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
Speck&Tech
 
Android with kotlin course
Android with kotlin courseAndroid with kotlin course
Android with kotlin course
Abdul Rahman Masri Attal
 
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
EastBanc Tachnologies
 
Kotlin Language powerpoint show file
Kotlin Language powerpoint show fileKotlin Language powerpoint show file
Kotlin Language powerpoint show file
Saurabh Tripathi
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
Gourav Kumar Saini
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
Rody Middelkoop
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
MobileAcademy
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptx
GDSCVJTI
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Android Programming Basics
Android Programming BasicsAndroid Programming Basics
Android Programming Basics
Eueung Mulyana
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
Aniruddha Chakrabarti
 
Android Components
Android ComponentsAndroid Components
Android Components
Aatul Palandurkar
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
Vladimir Parfenov
 
React native
React nativeReact native
React native
Mohammed El Rafie Tarabay
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Saba Ameer
 
Android Fragment
Android FragmentAndroid Fragment
Android Fragment
Kan-Han (John) Lu
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
Simplilearn
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
Speck&Tech
 
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
EastBanc Tachnologies
 
Kotlin Language powerpoint show file
Kotlin Language powerpoint show fileKotlin Language powerpoint show file
Kotlin Language powerpoint show file
Saurabh Tripathi
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
Rody Middelkoop
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
MobileAcademy
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptx
GDSCVJTI
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Android Programming Basics
Android Programming BasicsAndroid Programming Basics
Android Programming Basics
Eueung Mulyana
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Saba Ameer
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
Simplilearn
 

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
Mohamed Wael
 
Basics of kotlin ASJ
Basics of kotlin ASJBasics of kotlin ASJ
Basics of kotlin ASJ
DSCBVRITH
 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptx
adityakale2110
 
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
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
Syed Awais Mazhar Bukhari
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin
Zoran 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 development
Jayaprakash 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 love
André Oriani
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
Adit Lal
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
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
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
Matthew Clarke
 
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].pptx
kamalkantmaurya1
 
moocs_ppt.pptx
moocs_ppt.pptxmoocs_ppt.pptx
moocs_ppt.pptx
kamalkantmaurya1
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Fall in love with Kotlin
Fall in love with KotlinFall in love with Kotlin
Fall in love with Kotlin
Hari Vignesh Jayapalan
 
Lesson 1 Kotlin basics.pptx........................
Lesson 1 Kotlin basics.pptx........................Lesson 1 Kotlin basics.pptx........................
Lesson 1 Kotlin basics.pptx........................
21cse120tankalareshm
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
Magda Miu
 
Pembelajaran Basic Kotlin Kurikulum Google
Pembelajaran Basic Kotlin Kurikulum GooglePembelajaran Basic Kotlin Kurikulum Google
Pembelajaran Basic Kotlin Kurikulum Google
csgoservicecom
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
Mohamed Wael
 
Basics of kotlin ASJ
Basics of kotlin ASJBasics of kotlin ASJ
Basics of kotlin ASJ
DSCBVRITH
 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptx
adityakale2110
 
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
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin
Zoran 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 development
Jayaprakash 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 love
André Oriani
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
Adit 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 nigerians
junaidhasan17
 
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].pptx
kamalkantmaurya1
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Lesson 1 Kotlin basics.pptx........................
Lesson 1 Kotlin basics.pptx........................Lesson 1 Kotlin basics.pptx........................
Lesson 1 Kotlin basics.pptx........................
21cse120tankalareshm
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
Magda Miu
 
Pembelajaran Basic Kotlin Kurikulum Google
Pembelajaran Basic Kotlin Kurikulum GooglePembelajaran Basic Kotlin Kurikulum Google
Pembelajaran Basic Kotlin Kurikulum Google
csgoservicecom
 
Ad

Recently uploaded (20)

Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Journal of Soft Computing in Civil Engineering
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning ModelsMode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Journal of Soft Computing in Civil Engineering
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Redirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to RickrollsRedirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to Rickrolls
Kritika Garg
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
roshinijoga
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Redirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to RickrollsRedirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to Rickrolls
Kritika Garg
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
roshinijoga
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
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.!!
  翻译: