SlideShare a Scribd company logo
K O T L I N F O R A N D R O I D
D E V E L O P E R S
H A S S A N A B I D
C O N T E N T
• Why Kotlin
• Kotlin 101
• Kotlin vs. Java
• Advance Kotlin Topics
• Q & A
K O T L I N O N A N D R O I D S I N C E 2 0 1 7
K O T L I N 1 0 1
• It’s developed by JetBrains, and the fact that these are
the people behind a suite of IDEs, such as IntelliJ
• It’s pragmatic and concise, and makes coding a
satisfying and efficient experience.
• Kotlin is 100% interoperable with Java
S Y N TA X ( C L A S S )
class Foo {
val b: String = "b" // val means unmodifiable
var i: Int = 0 // var means modifiable
fun hello() {
val str = "Hello"
print("$str World")
}
fun sum(x: Int, y: Int): Int {
return x + y
}
fun maxOf(a: Float, b: Float) = if (a > b) a else b
}
S I N G L E L I N E
F U N C T I O N
S T R I N G I N T E R P O L AT I O N
// Java’s String.format() was built into the language
val x = 4
val y = 7
print("sum of $x and $y is ${x + y}") // sum of 4 and 7 is 11
T Y P E I N F E R E N C E
val a = "abc" // type inferred to String
val b = 4 // type inferred to Int
val c: Double = 0.7 // type declared explicitly
val d: List<String> = ArrayList() // type declared explicitly
S M A R T C A S T S
/* The Kotlin compiler tracks your logic and auto-casts types
if possible, which means no more instanceof checks
followed by explicit casts
*/
if (obj is String) {
print(obj.toUpperCase()) // obj is now known to be a String
}
I N T U I T I V E E Q U A L S
// no need to call equals()
val john1 = Person("John")
val john2 = Person("John")
john1 == john2 // true (structural equality)
john1 === john2 // false (referential equality)
D E FA U LT A R G U M E N T S
fun build(title: String, width: Int = 800, height: Int = 600) {
Frame(title, width, height)
}
N A M E D A R G U M E N T S
build("PacMan", 400, 300) // equivalent
build(title = "PacMan", width = 400, height = 300) // equivalent
build(width = 400, height = 300, title = "PacMan") // equivalent
W H E N E X P R E S S I O N ( S W I T C H )
when (x) {
1 -> print("x is 1")
2 -> print("x is 2")
3, 4 -> print("x is 3 or 4")
in 5..10 -> print("x is 5, 6, 7, 8, 9, or 10")
else -> print("x is out of range")
}
val res: Boolean = when {
obj == null -> false
obj is String -> true
else -> throw IllegalStateException()
}
P R O P E R T I E S
/*
Custom set & get behavior can be added to public fields,
which means we can stopbloating our code with mindless
getters & setters.
*/
class Frame {
var width: Int = 800
var height: Int = 600
val pixels: Int
get() = width * height
}
D E S T R U C T U R I N G D E C L A R AT I O N S
for ((key, value) in map) {
print("Key: $key")
print("Value: $value")
}
R A N G E S
for (i in 1..100) { ... }
for (i in 0 until 100) { ... }
for (i in 2..10 step 2) { ... }
for (i in 10 downTo 1) { ... }
if (x in 1..10) { ... }
E X T E N S I O N F U N C T I O N S
fun String.replaceSpaces(): String {
return this.replace(' ', '_')
}
val formatted = str.replaceSpaces()
N U L L S A F E T Y
/* Java is what we should call an almost statically typed language.
In it, a variable of type String is not guaranteed to
refer to a String— it might refer to null
*/
// Java developers have to live in constant fear of NPEs.
/* Kotlin resolves this by distinguishing between non-null
types and nullable types. Types are non-null by default,
and can be made nullable by adding a ? like so:
*/
var a: String = "abc"
a = null // compile error
var b: String? = "xyz"
b = null // no problem
N U L L S A F E T Y
//Kotlin forces you to guard against NPEs whenever
// you access a nullable type:
val x = b.length // compile error: b might be null
if (b == null) return
val x = b.length // no problem
/* We could also use a safe call ?.,
which evaluates to null instead of throwing a NPE:
*/
val x = b?.length // type of x is nullable Int
B E T T E R L A M A D A S
val sum = { x: Int, y: Int -> x + y } // type: (Int, Int) -> Int
val res = sum(4,7) // res == 11
numbers.filter({ x -> x.isPrime() })
numbers.filter { x -> x.isPrime() }
numbers.filter { it.isPrime() }
B E T T E R L A M A D A S
persons
.filter { it.age >= 18 }
.sortedBy { it.name }
.map { it.email }
.forEach { print(it) }
B E T T E R L A M A D A S
verticalLayout {
padding = dip(30)
editText {
hint = “Name”
textSize = 24f
}
editText {
hint = “Password”
textSize = 24f
}
button(“Login”) {
textSize = 26f
}
}
S C O P I N G F U N C T I O N S
// 1. with
val person: Person = getPerson()
with(person) {
print(name)
print(age)
}
// 2. apply
val peter = Person().apply {
// only access properties in apply block!
name = "Peter"
age = 18
}
S C O P I N G F U N C T I O N S
// 3. let
getNullablePerson()?.let {
// only executed when not-null
promote(it)
}
// 4. run
val inserted: Boolean = run {
val person: Person = getPerson()
val personDao: PersonDao = getPersonDao()
personDao.insert(person)
}
fun printAge(person: Person) = person.run {
print(age)
}
S C O P I N G F U N C T I O N S
private fun insert(user: User) = SqlBuilder().apply {
append("INSERT INTO user (email, name, age) VALUES ")
append("(?", user.email)
append(",?", user.name)
append(",?)", user.age)
}.also {
print("Executing SQL update: $it.")
}.run {
jdbc.update(this) > 0
}
K O T L I N E X T E N S I O N S -
K T X
K O T L I N E X T E N S I O N S F O R A N D R O I D
• Makes Android development more concise, pleasant
and idiomatic
• Writing clean, readable code is a lot easier and a lot
more fun
K T X E X A M P L E
view.addOnLayoutChangeListener(object : View.OnLayoutChangeListener
{ override fun onLayoutChange(
view: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
){
doSomething()
} })
K T X E X A M P L E
view.addOnLayoutChangeListener(object : View.OnLayoutChangeListener
{ override fun onLayoutChange(
view: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
){
doSomething()
} })
// KTX
view.doOnNextLayout { doSomething() }
S I N G L E L I N E
F U N C T I O N
A D D K T X I N Y O U R P R O J E C T
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0' }
A D D K T X I N Y O U R P R O J E C T
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0' }
M O R E K T X L I B S
androidx.core:core-ktx
androidx.fragment:fragment-ktx
androidx.palette:palette-ktx
androidx.sqlite:sqlite-ktx
androidx.collection:collection-ktx
androidx.lifecycle:lifecycle-viewmodel-ktx
androidx.lifecycle:lifecycle-reactivestreams-ktx
android.arch.navigation:navigation-common-ktx
android.arch.navigation:navigation-fragment-ktx
android.arch.navigation:navigation-runtime-ktx
android.arch.navigation:navigation-testing-ktx
android.arch.navigation:navigation-ui-ktx
android.arch.work:work-runtime-ktx
N A M E D PA R A M S A N D D E FA U LT VA L U E S
// Original drawable.setBounds(drawable.bounds.left,
drawable.bounds.top, drawable.bounds.right, 100)
// KTX
drawable.updateBounds(bottom = 100)
N A M E D PA R A M S A N D D E FA U LT VA L U E S
// Original
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationEnd(a: Animator?) { ... }
override fun onAnimationStart(a: Animator?) { }
override fun onAnimationCancel(a: Animator?) { }
override fun onAnimationRepeat(a: Animator?) { }
})
// KTX
animator.addListener(onEnd = { ... })
animator.doOnEnd { ... }
O P E R AT O R O V E R L O A D I N G
// Original
bitmap.getPixel(100, 100)
// KTX
bitmap[100, 100]
O P E R AT O R O V E R L O A D I N G
// Original
menu.removeItem(menuItem.itemId)
// KTX
menu -= menuItem
D E S T R U C T U R I N G
// Original
val lat = location.latitude
val long = location.longitude
// KTX
val (lat, long) = location
M O R E K T X E X A M P L E S
// Original
viewGroup.childCount != 0
// KTX
viewGroup.isEmpty() viewGroup.isNotEmpty()
// Original
for (index in 0 until viewGroup.childCount)
{ doSomething(viewGroup.getChildAt(index))
}x
// KTX
viewGroup.forEach { doSomething() }
M O R E K T X E X A M P L E S
// Original sharedPrefs.edit()
.putBoolean(key, valuex) .apply()
// KTX
sharedPrefs.edit { putBoolean(key, value) }
// Original
val builder = SpannableStringBuilder()
val start = builder.length builder.append("Hello") builder.setSpan(
StyleSpan(Typeface.BOLD),
start,
builder.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
// KTX
builder.bold { append("Hello") }
builder.bold { italic { underline { append("Hello") } } }
K O T L I N C O R O U N T I N E S
C O R O U T I N E S
• Light-weight threads (for async programming)
• Alternative to Rx-Java
S I M P L E A P P A R C H I T E C T U R E
C L E A N A R C H I T E C T U R E
O P E N S O U R C E C O D E
• https://github.com/nickbutcher/plaid
• https://github.com/googlesamples/android-sunflower
• https://github.com/bufferapp/android-clean-
architecture-boilerplate
L E A R N I N G M AT E R I A L
• Udacity
• https://www.udacity.com/course/developing-
android-apps-with-kotlin--ud9012
Q U E S T I O N S ?
T H A N K Y O U

More Related Content

What's hot

K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
Md Sazzad Islam
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
Andrey Breslav
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016
DesertJames
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
Yusuke Kita
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its tools
Max Andersen
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
Magda Miu
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with Kotlin
Haim Yadid
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
Bartosz Kosarzycki
 
Kotlin
KotlinKotlin
Monte Carlo C++
Monte Carlo C++Monte Carlo C++
Monte Carlo C++
Dmitri Nesteruk
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
Codemotion
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
Dinesh Manajipet
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
Vasil Remeniuk
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
intelliyole
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
Egor Bogatov
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
Bardia Heydari
 
Roslyn and C# 6.0 New Features
Roslyn and C# 6.0 New FeaturesRoslyn and C# 6.0 New Features
Roslyn and C# 6.0 New Features
Michael Step
 
Geospatial ETL with Stetl
Geospatial ETL with StetlGeospatial ETL with Stetl
Geospatial ETL with Stetl
Just van den Broecke
 

What's hot (20)

K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its tools
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with Kotlin
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
Kotlin
KotlinKotlin
Kotlin
 
Monte Carlo C++
Monte Carlo C++Monte Carlo C++
Monte Carlo C++
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Roslyn and C# 6.0 New Features
Roslyn and C# 6.0 New FeaturesRoslyn and C# 6.0 New Features
Roslyn and C# 6.0 New Features
 
Geospatial ETL with Stetl
Geospatial ETL with StetlGeospatial ETL with Stetl
Geospatial ETL with Stetl
 

Similar to Kotlin for Android Developers

The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
anand_study
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
Anass SABANI
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
Aveic
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+k
Fabio Collini
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal aka JOKER
 
Python crush course
Python crush coursePython crush course
Python crush course
Mohammed El Rafie Tarabay
 
Arrays
ArraysArrays
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
Muthu Vinayagam
 
WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0
Knoldus Inc.
 
Kotlin
KotlinKotlin
Fun with Kotlin
Fun with KotlinFun with Kotlin
Fun with Kotlin
Egor Andreevich
 
Let's fly to the Kotlin Island. Just an introduction to Kotlin
Let's fly to the Kotlin Island. Just an introduction to KotlinLet's fly to the Kotlin Island. Just an introduction to Kotlin
Let's fly to the Kotlin Island. Just an introduction to Kotlin
Aliaksei Zhynhiarouski
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
The STL
The STLThe STL
The STL
adil raja
 
2014-11-01 01 Денис Нелюбин. О сортах кофе
2014-11-01 01 Денис Нелюбин. О сортах кофе2014-11-01 01 Денис Нелюбин. О сортах кофе
2014-11-01 01 Денис Нелюбин. О сортах кофе
Омские ИТ-субботники
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
Tikal Knowledge
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
Nebojša Vukšić
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
league
 

Similar to Kotlin for Android Developers (20)

The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+k
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
Python crush course
Python crush coursePython crush course
Python crush course
 
Arrays
ArraysArrays
Arrays
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
 
WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0
 
Kotlin
KotlinKotlin
Kotlin
 
Fun with Kotlin
Fun with KotlinFun with Kotlin
Fun with Kotlin
 
Let's fly to the Kotlin Island. Just an introduction to Kotlin
Let's fly to the Kotlin Island. Just an introduction to KotlinLet's fly to the Kotlin Island. Just an introduction to Kotlin
Let's fly to the Kotlin Island. Just an introduction to Kotlin
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
The STL
The STLThe STL
The STL
 
2014-11-01 01 Денис Нелюбин. О сортах кофе
2014-11-01 01 Денис Нелюбин. О сортах кофе2014-11-01 01 Денис Нелюбин. О сортах кофе
2014-11-01 01 Денис Нелюбин. О сортах кофе
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
 

More from Hassan Abid

Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
Hassan Abid
 
Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)
Hassan Abid
 
Exploring CameraX from JetPack
Exploring CameraX from JetPackExploring CameraX from JetPack
Exploring CameraX from JetPack
Hassan Abid
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPack
Hassan Abid
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
Hassan Abid
 
Recap of Android Dev Summit 2018
Recap of Android Dev Summit 2018Recap of Android Dev Summit 2018
Recap of Android Dev Summit 2018
Hassan Abid
 
What's new in Android Pie
What's new in Android PieWhat's new in Android Pie
What's new in Android Pie
Hassan Abid
 
Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018
Hassan Abid
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
Hassan Abid
 
VR Video Apps on Daydream
VR Video Apps on DaydreamVR Video Apps on Daydream
VR Video Apps on Daydream
Hassan Abid
 
Best Practices in Media Playback
Best Practices in Media PlaybackBest Practices in Media Playback
Best Practices in Media Playback
Hassan Abid
 
ExoPlayer for Application developers
ExoPlayer for Application developersExoPlayer for Application developers
ExoPlayer for Application developers
Hassan Abid
 
Android n preview
Android n previewAndroid n preview
Android n preview
Hassan Abid
 
Introduction to Pakistan
Introduction to PakistanIntroduction to Pakistan
Introduction to Pakistan
Hassan Abid
 

More from Hassan Abid (14)

Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 
Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)
 
Exploring CameraX from JetPack
Exploring CameraX from JetPackExploring CameraX from JetPack
Exploring CameraX from JetPack
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPack
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Recap of Android Dev Summit 2018
Recap of Android Dev Summit 2018Recap of Android Dev Summit 2018
Recap of Android Dev Summit 2018
 
What's new in Android Pie
What's new in Android PieWhat's new in Android Pie
What's new in Android Pie
 
Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018Android Jetpack - Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
 
VR Video Apps on Daydream
VR Video Apps on DaydreamVR Video Apps on Daydream
VR Video Apps on Daydream
 
Best Practices in Media Playback
Best Practices in Media PlaybackBest Practices in Media Playback
Best Practices in Media Playback
 
ExoPlayer for Application developers
ExoPlayer for Application developersExoPlayer for Application developers
ExoPlayer for Application developers
 
Android n preview
Android n previewAndroid n preview
Android n preview
 
Introduction to Pakistan
Introduction to PakistanIntroduction to Pakistan
Introduction to Pakistan
 

Recently uploaded

Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 

Recently uploaded (20)

Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 

Kotlin for Android Developers

  • 1. K O T L I N F O R A N D R O I D D E V E L O P E R S H A S S A N A B I D
  • 2. C O N T E N T • Why Kotlin • Kotlin 101 • Kotlin vs. Java • Advance Kotlin Topics • Q & A
  • 3.
  • 4. K O T L I N O N A N D R O I D S I N C E 2 0 1 7
  • 5. K O T L I N 1 0 1 • It’s developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ • It’s pragmatic and concise, and makes coding a satisfying and efficient experience. • Kotlin is 100% interoperable with Java
  • 6. S Y N TA X ( C L A S S ) class Foo { val b: String = "b" // val means unmodifiable var i: Int = 0 // var means modifiable fun hello() { val str = "Hello" print("$str World") } fun sum(x: Int, y: Int): Int { return x + y } fun maxOf(a: Float, b: Float) = if (a > b) a else b } S I N G L E L I N E F U N C T I O N
  • 7. S T R I N G I N T E R P O L AT I O N // Java’s String.format() was built into the language val x = 4 val y = 7 print("sum of $x and $y is ${x + y}") // sum of 4 and 7 is 11
  • 8. T Y P E I N F E R E N C E val a = "abc" // type inferred to String val b = 4 // type inferred to Int val c: Double = 0.7 // type declared explicitly val d: List<String> = ArrayList() // type declared explicitly
  • 9. S M A R T C A S T S /* The Kotlin compiler tracks your logic and auto-casts types if possible, which means no more instanceof checks followed by explicit casts */ if (obj is String) { print(obj.toUpperCase()) // obj is now known to be a String }
  • 10. I N T U I T I V E E Q U A L S // no need to call equals() val john1 = Person("John") val john2 = Person("John") john1 == john2 // true (structural equality) john1 === john2 // false (referential equality)
  • 11. D E FA U LT A R G U M E N T S fun build(title: String, width: Int = 800, height: Int = 600) { Frame(title, width, height) }
  • 12. N A M E D A R G U M E N T S build("PacMan", 400, 300) // equivalent build(title = "PacMan", width = 400, height = 300) // equivalent build(width = 400, height = 300, title = "PacMan") // equivalent
  • 13. W H E N E X P R E S S I O N ( S W I T C H ) when (x) { 1 -> print("x is 1") 2 -> print("x is 2") 3, 4 -> print("x is 3 or 4") in 5..10 -> print("x is 5, 6, 7, 8, 9, or 10") else -> print("x is out of range") } val res: Boolean = when { obj == null -> false obj is String -> true else -> throw IllegalStateException() }
  • 14. P R O P E R T I E S /* Custom set & get behavior can be added to public fields, which means we can stopbloating our code with mindless getters & setters. */ class Frame { var width: Int = 800 var height: Int = 600 val pixels: Int get() = width * height }
  • 15. D E S T R U C T U R I N G D E C L A R AT I O N S for ((key, value) in map) { print("Key: $key") print("Value: $value") }
  • 16. R A N G E S for (i in 1..100) { ... } for (i in 0 until 100) { ... } for (i in 2..10 step 2) { ... } for (i in 10 downTo 1) { ... } if (x in 1..10) { ... }
  • 17. E X T E N S I O N F U N C T I O N S fun String.replaceSpaces(): String { return this.replace(' ', '_') } val formatted = str.replaceSpaces()
  • 18. N U L L S A F E T Y /* Java is what we should call an almost statically typed language. In it, a variable of type String is not guaranteed to refer to a String— it might refer to null */ // Java developers have to live in constant fear of NPEs. /* Kotlin resolves this by distinguishing between non-null types and nullable types. Types are non-null by default, and can be made nullable by adding a ? like so: */ var a: String = "abc" a = null // compile error var b: String? = "xyz" b = null // no problem
  • 19. N U L L S A F E T Y //Kotlin forces you to guard against NPEs whenever // you access a nullable type: val x = b.length // compile error: b might be null if (b == null) return val x = b.length // no problem /* We could also use a safe call ?., which evaluates to null instead of throwing a NPE: */ val x = b?.length // type of x is nullable Int
  • 20. B E T T E R L A M A D A S val sum = { x: Int, y: Int -> x + y } // type: (Int, Int) -> Int val res = sum(4,7) // res == 11 numbers.filter({ x -> x.isPrime() }) numbers.filter { x -> x.isPrime() } numbers.filter { it.isPrime() }
  • 21. B E T T E R L A M A D A S persons .filter { it.age >= 18 } .sortedBy { it.name } .map { it.email } .forEach { print(it) }
  • 22. B E T T E R L A M A D A S verticalLayout { padding = dip(30) editText { hint = “Name” textSize = 24f } editText { hint = “Password” textSize = 24f } button(“Login”) { textSize = 26f } }
  • 23. S C O P I N G F U N C T I O N S // 1. with val person: Person = getPerson() with(person) { print(name) print(age) } // 2. apply val peter = Person().apply { // only access properties in apply block! name = "Peter" age = 18 }
  • 24. S C O P I N G F U N C T I O N S // 3. let getNullablePerson()?.let { // only executed when not-null promote(it) } // 4. run val inserted: Boolean = run { val person: Person = getPerson() val personDao: PersonDao = getPersonDao() personDao.insert(person) } fun printAge(person: Person) = person.run { print(age) }
  • 25. S C O P I N G F U N C T I O N S private fun insert(user: User) = SqlBuilder().apply { append("INSERT INTO user (email, name, age) VALUES ") append("(?", user.email) append(",?", user.name) append(",?)", user.age) }.also { print("Executing SQL update: $it.") }.run { jdbc.update(this) > 0 }
  • 26.
  • 27. K O T L I N E X T E N S I O N S - K T X
  • 28. K O T L I N E X T E N S I O N S F O R A N D R O I D • Makes Android development more concise, pleasant and idiomatic • Writing clean, readable code is a lot easier and a lot more fun
  • 29. K T X E X A M P L E view.addOnLayoutChangeListener(object : View.OnLayoutChangeListener { override fun onLayoutChange( view: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int ){ doSomething() } })
  • 30. K T X E X A M P L E view.addOnLayoutChangeListener(object : View.OnLayoutChangeListener { override fun onLayoutChange( view: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int ){ doSomething() } }) // KTX view.doOnNextLayout { doSomething() } S I N G L E L I N E F U N C T I O N
  • 31. A D D K T X I N Y O U R P R O J E C T repositories { google() } dependencies { implementation 'androidx.core:core-ktx:1.0.0' }
  • 32. A D D K T X I N Y O U R P R O J E C T repositories { google() } dependencies { implementation 'androidx.core:core-ktx:1.0.0' }
  • 33. M O R E K T X L I B S androidx.core:core-ktx androidx.fragment:fragment-ktx androidx.palette:palette-ktx androidx.sqlite:sqlite-ktx androidx.collection:collection-ktx androidx.lifecycle:lifecycle-viewmodel-ktx androidx.lifecycle:lifecycle-reactivestreams-ktx android.arch.navigation:navigation-common-ktx android.arch.navigation:navigation-fragment-ktx android.arch.navigation:navigation-runtime-ktx android.arch.navigation:navigation-testing-ktx android.arch.navigation:navigation-ui-ktx android.arch.work:work-runtime-ktx
  • 34. N A M E D PA R A M S A N D D E FA U LT VA L U E S // Original drawable.setBounds(drawable.bounds.left, drawable.bounds.top, drawable.bounds.right, 100) // KTX drawable.updateBounds(bottom = 100)
  • 35. N A M E D PA R A M S A N D D E FA U LT VA L U E S // Original animator.addListener(object : Animator.AnimatorListener { override fun onAnimationEnd(a: Animator?) { ... } override fun onAnimationStart(a: Animator?) { } override fun onAnimationCancel(a: Animator?) { } override fun onAnimationRepeat(a: Animator?) { } }) // KTX animator.addListener(onEnd = { ... }) animator.doOnEnd { ... }
  • 36. O P E R AT O R O V E R L O A D I N G // Original bitmap.getPixel(100, 100) // KTX bitmap[100, 100]
  • 37. O P E R AT O R O V E R L O A D I N G // Original menu.removeItem(menuItem.itemId) // KTX menu -= menuItem
  • 38. D E S T R U C T U R I N G // Original val lat = location.latitude val long = location.longitude // KTX val (lat, long) = location
  • 39. M O R E K T X E X A M P L E S // Original viewGroup.childCount != 0 // KTX viewGroup.isEmpty() viewGroup.isNotEmpty() // Original for (index in 0 until viewGroup.childCount) { doSomething(viewGroup.getChildAt(index)) }x // KTX viewGroup.forEach { doSomething() }
  • 40. M O R E K T X E X A M P L E S // Original sharedPrefs.edit() .putBoolean(key, valuex) .apply() // KTX sharedPrefs.edit { putBoolean(key, value) } // Original val builder = SpannableStringBuilder() val start = builder.length builder.append("Hello") builder.setSpan( StyleSpan(Typeface.BOLD), start, builder.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE ) // KTX builder.bold { append("Hello") } builder.bold { italic { underline { append("Hello") } } }
  • 41. K O T L I N C O R O U N T I N E S
  • 42. C O R O U T I N E S • Light-weight threads (for async programming) • Alternative to Rx-Java
  • 43. S I M P L E A P P A R C H I T E C T U R E
  • 44. C L E A N A R C H I T E C T U R E
  • 45. O P E N S O U R C E C O D E • https://github.com/nickbutcher/plaid • https://github.com/googlesamples/android-sunflower • https://github.com/bufferapp/android-clean- architecture-boilerplate
  • 46. L E A R N I N G M AT E R I A L • Udacity • https://www.udacity.com/course/developing- android-apps-with-kotlin--ud9012
  • 47. Q U E S T I O N S ?
  • 48. T H A N K Y O U